<?php



namespace app\admin\controller;



use app\common\controller\Backend;

use \think\Db;

use think\Request;

use think\Cookie;





/**

 * 旅游产品主管理

 *

 * @icon fa fa-circle-o

 */

class Product extends Backend

{



    /**

     * Product模型对象

     * @var \app\admin\model\Product

     */

    protected $model = null;

    protected $fatherArr=array();



    //定义全局变量$senec_list 用于记录被删掉的产品标签，用于增加时判断

    protected $global_senec_list=[];

    public function _initialize()

    {

        parent::_initialize();

        $this->model = new \app\admin\model\Product;

        $this->model = model('app\admin\model\Product');



    }



    /**

     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法

     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑

     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改

     */



    /**

     * 产品列表查看

     *

     */

    function index()

    {



        $svalue=input("p_type");

        

        if(request()->isPost()){

            $stype=input("type");

            $svalue=input("p_type");

            $id=input("id");

            $p_no=input("p_no");

            $p_day=input("p_day");

            $p_name=input("p_name");

            $status=input("status");

            if($stype==""){



                if($id==""){

                    Cookie::delete('whereSearch');

                    if($status!=""){

                        Cookie::set('whereSearch',[6,$status]);

                    }

                    if($p_name!=""){

                        Cookie::set('whereSearch',[5,$p_name]);

                    }

                    if($p_day!=""){

                        Cookie::set('whereSearch',[4,$p_day]);

                    }

                    if($p_no!=""){

                        Cookie::set('whereSearch',[3,$p_no]);

                    }



                }else{



                    Cookie::set('whereSearch',[2,$id]);

                }



            }else{



                if($stype==0){



                    Cookie::delete('whereSearch');

                }else{



                    Cookie::set('whereSearch',[$stype,$svalue]);

                }



            }





        }

        $where=[];

        $search=[];

        if(isset($_COOKIE['whereSearch'])){







            $ws= Cookie::get('whereSearch');



            $stype1=$ws[0];

            $svalue1=$ws[1];

            if($stype1==1){

                if($svalue ==0){

                    $where['p_type']=array("in",'1,2,3,4');

                }else{

                    $where['p_type'] = $svalue;

                }

               

                $search["p_type"]=$svalue;

            }



            if($stype1==2){

                if($svalue ==0){

                    $where['p_type']=array("in",'1,2,3,4');

                }else{

                    $where['p_type'] = $svalue;

                }

                $where['id']=$svalue1;

                $search["id"]=$svalue1;

            }

            if($stype1==3){

                if($svalue ==0){

                    $where['p_type']=array("in",'1,2,3,4');

                }else{

                    $where['p_type'] = $svalue;

                }

                $where['p_no']=array("like","%".$svalue1."%");

                $search["p_no"]=$svalue1;

            }

            if($stype1==4){



                if($svalue ==0){

                    $where['p_type']=array("in",'1,2,3,4');

                }else{

                    $where['p_type'] = $svalue;

                }



                $where['p_day']=$svalue1;

                $search["p_day"]=$svalue1;

            }

            if($stype1==5){

                if($svalue ==0){

                    $where['p_type']=array("in",'1,2,3,4');

                }else{

                    $where['p_type'] = $svalue;

                }

                $where['p_name']=array("like","%".$svalue1 ."%");

                $search["p_name"]=$svalue1;

            }

            if($stype1==6){

                if($svalue1!=100){

                    if($svalue ==0){

                        $where['p_type']=array("in",'1,2,3,4');

                    }else{

                        $where['p_type'] = $svalue;

                    }

                    $where['status']=$svalue1;

                    $search["status"]=$svalue1;

                }else{

                    if($svalue ==0){

                        $where['p_type']=array("in",'1,2,3,4');

                    }else{

                        $where['p_type'] = $svalue;

                    }

                }



            }





        }else{

            if($svalue ==0){

                $where['p_type']=array("in",'1,2,3,4');

            }else{

                $where['p_type'] = $svalue;

            }

        }



        $status1=getArr("product-status");

        $data=db("product")->where($where)->order("id desc")->paginate(15,false,['query'=>request()->param()]);

      // var_dump(db("product")->getlastsql());

        //数据统计

        $page = $data->render();

        $list = $data->items();

        $product_mark=db("product_mark");

        $product_selfpay=db("product_selfpay");

        $user_evaluation=db("user_evaluation");

        $adsense=db("adsense");

        foreach($list as $k=>$v){

            // 标签统计

            $markCount=$product_mark->where("p_id",$v['id'])->count();

            $list[$k]['mark_count']=$markCount;

            //自费项目统计

            $result=$product_selfpay->where(["pid"=>$v['id'],"pptype"=>0])->find();

            if($result){

                $count=$this->getSelfCount($result['id']);

            }else{

                $count=0;

            }

            $list[$k]['self_pay_count']=$count;

            //产品点评

            $evaluationListCount=$user_evaluation->where(['pid'=>$v['id']])->count();

            $list[$k]['evaluation_count']=$evaluationListCount;

            //关联推荐产品

            $adsenseRes=$adsense->where("p_id",$v['id'])->find();

            if($adsenseRes){

                $adsenseCount=$this->getAdsenseCount($adsenseRes['id']);

            }else{

                $adsenseCount=0;

            }

            $list[$k]['adsense_count']=$adsenseCount;

        }







        $this->view->assign([

            "list"=>$list,

            'status1'=>$status1,

            'search'=>$search,

            'page'=>$page,

            'p_type'=>$svalue

        ]);

        return $this->view->fetch();

    }



    //获取关联推荐产品个数

    public function getAdsenseCount($sense_id){

        $ad=db("ad");

        $adCount=$ad->where("sense_id",$sense_id)->count();

        return $adCount;

    }



    //获取自费项目个数

    public function getSelfCount($id){

        $count=0;

        $product_selfpay=db("product_selfpay");

        $list1=$product_selfpay->where(["fid"=>$id,"pptype"=>1])->select();

        if(is_array($list1)){

            foreach($list1 as $k=>$v){

                $list2=$product_selfpay->where(["fid"=>$v['id'],"pptype"=>2])->select();

                if(is_array($list2)){

                    foreach($list2 as $k1=>$v1){

                        $count_3=$product_selfpay->where(["fid"=>$v1['id'],"pptype"=>3])->count();

                        $count=$count+$count_3;

                    }

                }else{

                    $count=0;

                }

            }

        }else{

            $count=0;

        }

        return $count;



    }





    /**

     *产品增加

     *

     */



    function product_add()

    {

        $product=db("product");

        $p_type=getArr("product-p_type");

        $season=getArr("product-season");

        if(request()->isPost()){

            $day=input("p_day");

            $p_no=input("p_no");

            $result=db("product")->where("p_no",$p_no)->find();

            if($result){

                $this->error("产品编号已经存在！");



            }

            $season_type=input("season");

            $type=input("p_type");

            $data['p_name']=input("p_name");

            $data['s_name']=input("s_name");

            $data['e_name']=input("e_name");

            $data['status']=0;

            $data['p_no']=$p_no;

            $data['p_type']=input("p_type");

            //$data['startcity']=input("startcity");

            //$data['endcity']=input("endcity");

            $data['transport']=input("transport");

            $data['marktype']=input("marktype");

            $data['children']=input("children");

            // $data['p_day']=input("p_day");

            $data['pricetype']=input("pricetype");

            if($type==1 || $type==3){

                $data['g_p_type']=1;

            }elseif($type==2){

                $data['g_p_type']=2;

            }else{

                $data['g_p_type']=input("g_p_type");

            }

            //$data['g_p_type']=input("g_p_type");

            $data['userid']=$_SESSION['think']['admin']['id'];

            $data['username']=$_SESSION['think']['admin']['username'];

            $data['c_time']=time();//unset($data['file'])

            //dump($data);die;



            $res=$product->insertGetId($data);//返回自增主键值

            if($res){

                $numId=db("num")->find();

                /*if($numId['pno']>=4000){

                    $poId=$numId['pno']+1;

                }else{

                    $poId=4000;

                }*/

                //$p_no=input("p_no")."-".$poId;

                $linkno=$numId['linkno']+1;



                //设置关联产品的初始化数据

                $product->where("id",$res)->setField("p_no",$p_no);

                $data1['linkno']=$linkno;

                $data1['p_id']=$res;

                $data1['title']='A';

                db("product_link")->insert($data1);

               // $data2['pno']=$poId;

              //  $data2['linkno']=$linkno;

              //  db("num")->where("id",1)->setField($data2);

                $this->model = model('app\admin\model\Product');

                $this->model->product_add_M($day,$res,input("pricetype"));





                //默认添加产品信息

                $product_info_type=getArr("product-info-type");

                $product_info=db("product_info");



                //    '1'=>'产品特色',

                $product_data1['p_id']=$res;

                $product_data1['info_type']=1;

                $product_data1['title']=$product_info_type[1];

                $product_data1['fid']=0;

                $product_data1['status']=0;

                $product_data1_res=$product_info->insertGetId($product_data1);



                // '2'=>'费用说明',

                $product_data2['p_id']=$res;

                $product_data2['info_type']=2;

                $product_data2['title']=$product_info_type[2];

                $product_data2['fid']=0;

                $product_data2['status']=0;

                $product_data2_res=$product_info->insertGetId($product_data2);

                //  '3'=>'费用包含',

                $product_data3['p_id']=$res;

                $product_data3['info_type']=3;

                $product_data3['title']=$product_info_type[3];

                $product_data3['fid']=$product_data2_res;

                $product_data3['status']=0;

                $product_data3_res=$product_info->insertGetId($product_data3);

                //    '4'=>'费用不包含',

                $product_data4['p_id']=$res;

                $product_data4['info_type']=4;

                $product_data4['title']=$product_info_type[4];

                $product_data4['fid']=$product_data2_res;

                $product_data4['status']=0;

                $product_data4_res=$product_info->insertGetId($product_data4);



                // '5'=>'签证说明',

                $product_data5['p_id']=$res;

                $product_data5['info_type']=5;

                $product_data5['title']=$product_info_type[5];

                $product_data5['fid']=0;

                $product_data5['status']=0;

                $product_data5_res=$product_info->insertGetId($product_data5);



                //预定须知

                $product_data6['p_id']=$res;

                $product_data6['info_type']=6;

                $product_data6['title']=$product_info_type[6];

                $product_data6['fid']=0;

                $product_data6['status']=0;

                $product_data6_res=$product_info->insertGetId($product_data6);

                // '9'=>'安全须知',

                $product_data9['p_id']=$res;

                $product_data9['info_type']=9;

                $product_data9['title']=$product_info_type[9];

                $product_data9['fid']=$product_data6_res;

                $product_data9['status']=0;

                $product_data9_res=$product_info->insertGetId($product_data9);

                // '8'=>'购买须知',

                $product_data8['p_id']=$res;

                $product_data8['info_type']=8;

                $product_data8['title']=$product_info_type[8];

                $product_data8['fid']=$product_data6_res;

                $product_data8['status']=0;

                $product_data8_res=$product_info->insertGetId($product_data8);

                // '7'=>'常见问题',

                $product_data7['p_id']=$res;

                $product_data7['info_type']=7;

                $product_data7['title']=$product_info_type[7];

                $product_data7['fid']=0;

                $product_data7['status']=0;

                $product_data7_res=$product_info->insertGetId($product_data7);



                //'11'=>'推荐理由',

                $product_data11['p_id']=$res;

                $product_data11['info_type']=11;

                $product_data11['title']=$product_info_type[11];

                $product_data11['fid']=0;

                $product_data11['status']=0;

                $product_data11_res=$product_info->insertGetId($product_data11);



                $this->success("数据添加成功",'index');

            }else{

                $this->error("数据添加失败");

            }

        }



        $this->assign([

            'p_type'=>$p_type,

            'season'=>$season,

        ]);

        //获取代理商信息用于新增选择





        $agent=db("agent")->where("status",0)->select();

        $this->view->assign("agent", $agent);

        return $this->view->fetch();

    }



    /**

     *产品修改

     *

     */

    function product_edit()

    {

        $product=db("product");

        $p_type=getArr("product-p_type");

        $status=getArr("product-status");

        $id=input("id");

        $res=$product->find($id);

       /* $p_no=$res['p_no'];

        $arr_no=explode("-",$p_no);

        $p_no_1=$arr_no[0];

        $p_no_2=$arr_no[1];*/

        //获取产品信息表里的推荐理由



        $product_info_text="";

       $product_info=db("product_info")->where("p_id=".$id." and info_type=11")->find();

       if($product_info){

           $product_info_text=$product_info['info'];

       }





        // dump($res);//die;

        if(request()->isPost()){

            $data=input("post.");

            //$data['p_no']=$data['p_no']."-".$p_no_2;





            //删除推荐理由并加入新的推荐理由

            $prodct_info_new=[];

            $prodct_info_new['p_id']=$data['id'];

            $prodct_info_new['info_type']=11;

            $prodct_info_new['title']="推荐理由";

            $prodct_info_new['info']=$data['info'];

            $prodct_info_new['fid']=0;

            $prodct_info_new['status']=0;

            db("product_info")->where("p_id=".$data['id']." and info_type=11")->delete();

            db("product_info")->insert($prodct_info_new);

            unset($data['info']);

            $update=$product->update($data);

            $this->success("数据修改成功","index");

        }

        $agent=db("agent")->where("status",0)->select();



        $this->assign([

            'p_type'=>$p_type,

            'status'=>$status,

            'res'=>$res,

            ///'p_no_1'=>$p_no_1,

            'p_info'=>$product_info_text,

            'agent'=>$agent,

        ]);



        return $this->view->fetch();

    }





    /**

     *产品删除

     *

     */

    function product_del()

    {



        if(request()->isAjax()){

            $id=input("post.id");

            //dump($id);die;

            //产品标签删除

            $product_mark=db("product_mark");

            $productMarkList=$product_mark->where("p_id",$id)->select();

            // dump($productMarkList);//die;

            if(!empty($productMarkList)){

                foreach($productMarkList as $k=>$v){

                    $resultMarkRes=$product_mark->delete($v['id']);

                    if(!$resultMarkRes){

                        ajaxMsg("产品标签删除失败",0);

                    }

                }

            }

            //产品信息删除

            $product_info=db("product_info");

            $product_info_img=db("product_info_img");

            $productInfoList=$product_info->where("p_id",$id)->select();

            //dump($productInfoList);//die;

            if(!empty($productInfoList)){

                foreach($productInfoList as $k=>$v){

                    $productInfoImgList=$product_info_img->where("pi_id",$v['id'])->select();

                    foreach($productInfoImgList as $k1=>$v1){

                        //dump($thumb);die;

                        $imgpath=ROOT_PATH . 'public'.$v1['imgurl'];

                        //删除图片文件(夹)

                        @unlink($imgpath);

                        //删除图片库中info子数据

                        $resultProductInfoImgRes=$product_info_img->delete($v1['id']);

                        if(!$resultProductInfoImgRes){

                            ajaxMsg("产品信息图片删除失败",0);

                            return;

                        }

                    }

                    $resultProductInfoRes=$product_info->delete($v['id']);

                    if(!$resultProductInfoRes){

                        ajaxMsg("产品信息删除失败",0);

                    }

                }

            }

            ///  //产品图片删除

            $product_adimg=db("product_adimg");

            $productAddImgList=$product_adimg->where("p_id",$id)->select();

            ///dump($productAddImgList);//die;

            if(!empty($productAddImgList)){

                foreach($productAddImgList as $k=>$v){

                    $imgpath=ROOT_PATH . 'public'.$v['imgurl'];

                    @unlink($imgpath);

                    $resultProductAdImgRes=$product_adimg->delete($v['id']);

                    if(!$resultProductAdImgRes){

                        ajaxMsg("产品图片删除失败",0);

                    }

                }

            }

            //产品套餐信息

            $product_package=db("product_package");

            $productPacageList=$product_package->where("p_id",$id)->select();



            // dump($productPacageList);die;

            if(!empty($productPacageList)){

                foreach($productPacageList as $k=>$v){

                    $this->package_common_del($v['id'],$v['p_id']);

                }

            }



            //自费项目删除

            $product_selfpay=db("product_selfpay");

            $productSelfPayList=$product_selfpay->where("pid",$id)->select();

            if(!empty($productSelfPayList)){

                foreach($productSelfPayList as $k=>$v){

                    $this->chargeable_common_del($v['id']);

                }

            }

            //产品删除 主表

            //dump($id);

            $productRes=db("product")->delete($id);

            //dump($productRes);die;



            db("homelist")->where("pid=".$id)->delete();

            db("temp")->where("id2=".$id)->delete();

            if($productRes){

                ajaxMsg("产品删除成功",1);

            }else{

                ajaxMsg("产品删除失败",0);

            }

        }

    }





    public function package_common_del($package_id,$pid){



        $res=db("product_package")->where(["id"=>$package_id,"p_id"=>$pid])->find();

        $list=db("product_package")->where(["p_id"=>$pid])->select();

        //dump($res);

        $lists=$this->package_resort($list,$package_id,$res['pptype']);

        foreach($lists as $k=>$v){

            if($v['pptype']==2){

                $wherep['p_id']=$v['p_id'];

                $wherep['pa_showchar']=array("gt",$v['pa_showchar']);

                $packArr=db("product_package")->where($wherep)->select();

                foreach($packArr as $k3=>$v3){

                    $str=ord($v3['pa_showchar'])-1;

                    $char=chr($str);

                    db("product_package")->where("id",$v3['id'])->update(['pa_showchar'=>$char]);

                }

                //删除团期

                $groupList=db("product_group")->where(['p_id'=>$v['p_id'],"package_id"=>$v['id']])->select();

                foreach($groupList as $k1=>$v1){



                    $groupPrice=db("product_price_a")->where(['p_id'=>$v1['p_id'],"group_id"=>$v1['id'],"package_id"=>$v1['package_id']])->select();

                    foreach($groupPrice as $k2=>$v2){

                        $price_result=db("product_price_a")->delete($v2['id']);

                        if(!$price_result){

                            ajaxMsg("套餐团期价格删除失败",0);

                        }

                    }

                    $result=db("product_group")->delete($v1['id']);

                    if(!$result){

                        ajaxMsg("套餐团期删除失败",0);

                    }

                }

                //route_common_del($id,$pid)

                $this->route_common_del($v['id'],$v['p_id']);



            }



            db("product_package")->delete($v['id']);

        }

        db("product_package")->delete($package_id);

    }



    public function chargeable_common_del($id){

        $product_selfpay=db("product_selfpay");

        $res=$product_selfpay->field("*")->where("id",$id)->find();

        $data=$product_selfpay->field("*")->where(['pid'=>$res['pid']])->select();

        $list=$this->resort($data,$id,$res['pptype']);

        foreach($list as $k=>$v){

            if($v['pptype']==3){

                $spprice_list=db("product_spprice")->where("sp_id",$v['id'])->select();

                foreach($spprice_list as $k1=>$v1){

                    $spprice_list_res=db("product_spprice")->delete($v1['id']);

                }

            }

            $son_id=$product_selfpay->delete($v['id']);



        }



        $result=$product_selfpay->delete($id);

    }







    function group_package()

    {

        $pid=input("get.pid");

        $p_type=input("get.p_type");

        $list=db("product_package")->where(["p_id"=>$pid,'pptype'=>2])->select();
       

        foreach($list as $k=>$v){

            $res=db("product_package")->field("ptitle")->where("id",$v['fid'])->find();

            //$count=db('route')->where(["p_id"=>$pid,"package_id"=>$v['id']])->count();

            $list[$k]['father_title']=$res['ptitle'];

            // $list[$k]['count']=$count;



        }

     

        $pptype=getArr('package-type');

        $this->assign([

            'list'=>$list,

            'pptype'=>$pptype,

            'p_type'=>$p_type,

        ]);

        return $this->view->fetch();

    }







    /**

     *团期列表

     *

     */

    function group_index()

    {

        //$this->model = model('app\admin\model\Product');

        // $list=collection($this->model->order('id desc')->select())->toArray();

        $list=db('product_group')->where("p_id=".input('p_id')." and package_id=".input('package_id'))->order('g_time asc')->select();



        for($i=0;$i<count($list);$i++){

            $pricelist=db("product_price_a")->where("group_id=".$list[$i]['id'])->order("p_num")->select();

            $plstr="";

            $plstr1="";

            foreach($pricelist as $k =>$v) {

                $plstrinfo=$v['p_num']."#".$v['price']."#".$v['title']."#".$v['info'];

                $plstr=$plstr.$plstrinfo."@";

                $plstr1=$plstr1.$v['price']."|";

            }

            if(mb_strlen($plstr,'UTF8')!=0){

                $plstr=mb_substr($plstr,0,mb_strlen($plstr,'UTF8')-1);

            }

            $list[$i]["pricelist"]=$plstr;

            $list[$i]["price"]=$plstr1;

        }



        $selfpaylist=db("product_selfpay")->where("pid=".input('p_id')." and fid=0")->order("pa_order")->select();



        $this->view->assign("selfpaylist", $selfpaylist);

        $this->view->assign("list", $list);

        $this->view->assign("p_id", input('p_id'));

        $this->view->assign("package_id", input('package_id'));

        return $this->view->fetch();

    }



    /**

     *团期增加,修改，删除

     *

     */

    function group_add()

    {



        $p_id=input("p_id");

        $package_id=input("package_id");

        if(input("action")=='add'){



            //获取参数

            $g_max=input("g_max");

            $status=input("status");

            $selfpayid=input("selfpayid");

            $discount=input("discount");

            $childrenprice=input("childrenprice");

            $onehouse=input("onehouse");

            $discounttype=input("discounttype");

            $industry_share=input("industry_share");

            $glist1=input("glist1");

            $garr1 = explode("|", $glist1);



            unset($garr1[0]);

            $garr1 = array_values($garr1);

            $glist2=input("glist2");



            $garr2 = explode("|", $glist2);



            unset($garr2[0]);

            $garr2 = array_values($garr2);

            //获取价格数组字符串

            $pricestr=input("pricestr");

            //$pieces = explode("@", $pricestr);

            //获取需要更新字段的数组

            $sele="";

            if(isset($_POST["sele"])){

                $sele=$_POST["sele"];

            }

            $sele=$_POST["sele"];



            for($i=0;$i<count($garr1);$i++){



                if(isset($sele['is_g_max'])){

                    $data['g_max']=$g_max;

                }

                if(isset($sele['is_status'])){

                    $data['status']=$status;

                }

                if(isset($sele['is_discount'])){

                    $data['discount']=$discount;

                }

                if(isset($sele['is_childrenprice'])){

                    $data['childrenprice']=$childrenprice;

                }

                if(isset($sele['is_onehouse'])){

                    $data['onehouse']=$onehouse;

                }

                if(isset($sele['is_discounttype'])){

                    $data['discounttype']=$discounttype;

                }

                if(isset($sele['is_industry_share'])){

                    $data['industry_share']=$industry_share;

                }

                if(isset($sele['is_selfpayid'])){

                    $data['selfpay_id']=$selfpayid;

                }

                $data['g_time']=strtotime($garr1[$i]." 0:0:0");

                $data['p_id']=$p_id;

                $data['package_id']=$package_id;

                $this->model = model('app\admin\model\Product');

               $insergroupid= $this->model->productgroup_add_M($data,$pricestr,isset($sele['is_price']));



                db("product_group")->where(["p_id"=>$p_id,"g_time"=>$data['g_time']])->update(["selfpay_id"=>$selfpayid]);





                //更新团期最低价

                $this->model->getgpest($insergroupid);



            }

            $data=[];

            for($i=0;$i<count($garr2);$i++){

                if(isset($sele['is_g_max'])){

                    $data['g_max']=$g_max;

                }

                if(isset($sele['is_status'])){

                    $data['status']=$status;

                }

                if(isset($sele['is_discount'])){

                    $data['discount']=$discount;

                }

                if(isset($sele['is_childrenprice'])){

                    $data['childrenprice']=$childrenprice;

                }

                if(isset($sele['is_onehouse'])){

                    $data['onehouse']=$onehouse;

                }

                if(isset($sele['is_discounttype'])){

                    $data['discounttype']=$discounttype;

                }

                if(isset($sele['is_industry_share'])){

                    $data['industry_share']=$industry_share;

                }

                if(isset($sele['is_selfpayid'])){

                    $data['selfpay_id']=$selfpayid;

                }

                $data['p_id']=$p_id;

                $data['package_id']=$package_id;

                $this->model = model('app\admin\model\Product');

                $this->model->productgroup_edit_M( $garr2[$i],$data,$pricestr,isset($sele['is_price']));

               //更新团期最低价

                $this->model->getgpest($garr2[$i]);

                //更新团期自费项目id

                $g_time=Db::name('product_group')->field("g_time")->where(['id' => $garr2[$i]])->find();



                db("product_group")->where("p_id=".$p_id." and g_time=".$g_time['g_time'])->update(["selfpay_id"=>$selfpayid]);

            }

            //更新产品最低价和最高折扣

            $this->model->getpriceest($p_id);



        }

        if(input("action")=='del'){

            //获取参数

            $glist2=input("glist2");

            $garr2 = explode("|", $glist2);

            unset($garr2[0]);

            $garr2 = array_values($garr2);

            for($i=0;$i<count($garr2);$i++){

                $this->model = model('app\admin\model\Product');

                $this->model->productgroup_del_M( $garr2[$i]);

            }

            $this->model->getpriceest($p_id);

            }



        //echo '/admin/product/group_index?p_id='.$p_id."&package_id=".$package_id;

       $this->redirect('/admin/product/group_index?p_id='.$p_id."&package_id=".$package_id);

    }



    public function route_edit(){

        if(Request()->isAjax()){

            //dump(input("post."));die;

            $p_id=input("p_id");

            $titlearr=input("titlearr");

            $tr_id=input("tr_id");

            $this->model = model('app\admin\model\Product');

            $data= [

                'p_id' => $p_id,

                'titlearr' => $titlearr,

                'tr_id' => $tr_id,

            ];

            $res=$this->model->route_edit_M($data);

            if($res){

                echo 1;

            }else{

                echo 0;

            }



        }else{

            return $this->view->fetch();

        }

    }

    /**

     *天数删除

     *

     */

    function route_delday()

    {



        //获取删除id

        $id=input("id");



        //获取产品id

        $p_id=input("p_id");



        $this->model = model('app\admin\model\Product');



        //删除操作，需要两个参数，删除的id，和产品id

        $inid=$this->model->route_del_M($id,$p_id);



        $this->redirect('/admin/product/route_index?p_id='.$p_id);

    }









    /**

     *行程具体内容增加和修改

     *

     */

    public function route_info_add(){

        if(Request()->isAjax()){

            $tr_id=input("trid");

            $title=input("title");

            $info=htmlspecialchars_decode(input("info"));

            $itype=input("itype");

            $tagid=input("tagid");

            $linkid=input("linkid");



            $data= [

                'tr_id' => $tr_id,

                'title' => $title,

                'info' => $info,

                'itype' => $itype,

                'tagid' => $tagid,

                'linkid' => $linkid,

            ];

           // dump($data);die;

            $this->model = model('app\admin\model\Product');

            $inid= $this->model->product_add_info_M($data);

            if($inid){

                echo 1;

            }else{

                echo 0;

            }



        }else{

            return $this->view->fetch();

        }





    }



    /**

     *行程具体内容增加和修改

     *

     */

    public function route_info_edit(){

       // dump(input("get."));

        if(Request()->isAjax()){

            $id=input("id");

            $data=[

              'title'=>input("title"),

                'info'=>htmlspecialchars_decode(input("info")),

                'linkid'=>input("linkid"),

            ];

            $this->model = model('app\admin\model\Product');

            $result=$this->model->product_edit_info_M($id,$data);

            if($result){

                echo 1;

            }else{

                echo 0;

            }



        }else{

            $id=input("id");

            $res=db("route_info")->find($id);



            $placeid=$res['linkid'];

            $placename="";

            if($placeid){

                $placeinfo=db("place")->find($placeid);

                $placename=$placeinfo['full_name'];

            }





            $this->assign("placename",$placename);

            $this->assign("res",$res);

            return $this->view->fetch();

        }



    }

    /**

     *单一一天某内容删除

     *

     */

    public function del_info(){

        if(Request()->isAjax()){

            $id=input("id");

            $route_info=db("route_info")->find($id);

            $list=db("route_info_img")->where("tri_id",$id)->select();

            foreach ($list as $k=>$v){

                $thumb=explode("/",$v['imgadr']);

                //dump($thumb);die;

                $thumb_img=ROOT_PATH . 'public'."/".$thumb['1']."/".$thumb['2']."/"."200_120"."/".$thumb['3'];

                $imgpath=ROOT_PATH . 'public'.$v['imgadr'];

                //删除图片文件(夹)

                if($route_info['itype']!=7){

                    @unlink($imgpath);

                    @unlink($thumb_img);

                }



                db("route_info_img")->delete($v['id']);

            }

            $result=db("route_info")->delete($id);

            if($result){

                echo 1;

            }else{

                echo 0;

            }

        }

    }



    /**

     *行程天数内容删除

     *

     */

    function route_info_del()

    {

        //获取删除id

        if(Request()->isAjax()){

            $id=input("id");

            $routeRes=db("route")->find($id);

            $this->model = model('app\admin\model\Product');

            $res=$this->model->product_del_info_M($id);

            set_route_day($routeRes['p_id'],$routeRes['package_id']);

           if($res){

               echo 1;

           }else{

               echo 0;

           }

        }





    }



    /**

     *行程详情增加图片

     *田博 20190909

     */

    public function route_info_img_add(){

        $width=200;

        $height=120;

        $data=input("post.");

        //dump($data);//die;



        if($data['img']!=''){

            $img=base64_image_content($data['img']);

            $route_info=db("route_info");

            $route_info_res=$route_info->find($data['tr_id']);

             // dump($route_info_res);//die;

            $place=db("place")->where("id",$route_info_res['linkid'])->find();

            //dump($place);//die;



            $res= [

                'imgadr' => $img['url'],

                'tri_id' => $data['tr_id'],

            ];



            $this->model->product_add_info_img_M($res);





            if($route_info_res['itype']==7){

                if($data['is_img1']==0){

                    $img1=base64_image_content1($data['img1'],$place['id']);

                   // dump($img1);die;

                    set_place_media($place['id'],0,$img1['url'],$place['p_name'],"",0);

                }

                set_place_media($place['id'],0,$img['url'],$place['p_name'],"",1);

            }





            $imgpath=ROOT_PATH . 'public'.$img['url'];

            $date_path =ROOT_PATH . 'public'."/"."uploads"."/".$img['time']."/".$width.'_'.$height;

            $image = \think\Image::open($imgpath);

            if(!file_exists($date_path)){

                mkdir($date_path,0777,true);

            }

            $thumb_path = $date_path.'/'.$img['base_name'];

           // $image->thumb($width, $height)->save($thumb_path);

            echo 1;

        }else{

            echo 0;

        }

    }













    /**

     *行程详情图片详情删除

     *20190909  田博

     */



    public function delSingInfo(){

        //ROOT_PATH . 'public'."/"."uploads"."/".$img['time']."/".$width.'_'.$height;

        $width=200;

        $height=120;

        $route_info_img=db("route_info_img");

        $id=input("id");

        $res=$route_info_img->find($id);

        $route_info=db("route_info")->find($res['tri_id']);

        $img=$res['imgadr'];

        //dump($img);

        $thumb_url=explode("/",$res['imgadr']);

        //dump($thumb_url);

        $img_url=ROOT_PATH . 'public'.$res['imgadr'];

        // dump($img_url);

        $thumb_img_url=ROOT_PATH . 'public'."/".$thumb_url[1]."/".$thumb_url[2]."/".$width.'_'.$height."/".$thumb_url[3];

        // dump($thumb_img_url);

        $result=$route_info_img->delete($id);

        if($result){

            if($route_info['itype']!=7){

                @unlink($img_url);

                @unlink($thumb_img_url);

            }

            echo 1;

        }else{

            echo 0;

        }

    }





    /**

     *产品信息维护列表

     * 田博--190826

     */



    public function info_index(){

        $pid=input("p_id");

        //dump($pid);

        $info_type=getArr('product-info-type');

        $info=db("product_info");

        $where['p_id']=$pid;

        $where['fid']=0;

        $list=$info->where($where)->order("info_order desc")->select();

        foreach ($list as $k=>$v){

            $list1=$info->where('fid',$v['id'])->order("info_order desc")->select();

            $list[$k]['child']=$list1;

        }





        if(request()->isPost()){

            $data=input("post.");

            //dump($data);die;

            foreach ($data as $k=>$v){

                $info->where("id",$k)->setField("info_order",$v);

            }

            $this->success("排序修改成功");

        }



        $this->assign([

            'list'=>$list,

            'pid'=>$pid,

            'info_type'=>$info_type,

        ]);

        return $this->view->fetch();



    }





    /**

     *产品信息添加图片

     * 田博--190911

     */



    public function info_img_add(){

        $product_info_img=db("product_info_img");

        // dump(input("get."));

        $pid=input("id");

        $list=$product_info_img->where("pi_id",$pid)->order("i_order asc")->select();

        // dump($list);

        $this->assign("list",$list);

        if(request()->isPost()){

            $data=input("post.");

            //dump($data);die;

            if($list){

                foreach ($list as $k=>$v){

                    $res_path=ROOT_PATH . 'public' .$v['imgurl'];

                    $product_info_img->delete($v['id']);

                    @unlink($res_path);

                }

            }



            if($_FILES['file']['tmp_name']){

                // dump($_FILES);die;

                $file = request()->file("file");

                $filePaths = ROOT_PATH . 'public' . DS . 'uploads' . DS ;

                if(!file_exists($filePaths)){

                    mkdir($filePaths,0777,true);

                }

                $name_info=$file->getInfo();

               // dump($name_info);

                $name=date("Ymd",time())."/".mt_rand(10000,99999).substr($name_info['name'],-4);

                $info = $file->move($filePaths,$name);

               // dump($info);die;

                if($info){

                    ini_set ("memory_limit","2048M") ;

                    set_time_limit(0);



                    $imgpath = $info->getPath()."/".$info->getBasename();

                    $image = \think\Image::open($imgpath);

                    $width=$image->width();

                    $height=$image->height();

                    $pier=500;

                    $num=ceil($height/$pier);

                   // dump($num);//die;

                    for($i=0;$i<=$num-1;$i++){

                        $image = \think\Image::open($imgpath);

                        $migration=$i*$pier;

                        if($i==($num-1)){

                            $pier=$height-$i*$pier;

                        }

                        $order=$i+1;

                        $date=date("Ymd",time());

                        $path=$info->getPath()."/"."$order".$info->getBasename();

                        $url="/uploads/".$date."/"."$order".$info->getBasename();

                        $image->crop($width,$pier,0,$migration)->save($path);

                        $insert['i_order']=$order;

                        $insert['pi_id']=$data['id'];

                        $insert['imgurl']=$url;

                        db("product_info_img")->insert($insert);
                        
                    }
                   
                   
                    unset($info);

                    @unlink($imgpath);
                    echo "<script>alert('上传成功!');history.back();</script>";
                
                }else{

                    return $file->getError();

                }



            }

        }



        return $this->view->fetch();

    }





    /**

     *产品图片添加

     * 田博--190910

     */

    public function index_add_img(){

        $pid=input("pid");

        if(request()->isPost()){

            $data=input("post.");

            $data['ismain']=0;

            $data['p_id']=$pid;

            if($data['imgurl']!=''){

                $img=base64_image_content($data['imgurl']);

                $data['imgurl']=$img['url'];

            }

            //dump($data);die;

            $add=db("product_adimg")->insert($data);

            if($add){

                $this->success("数据添加成功","/admin/product/index_img?id={$pid}");

            }else{

                $this->error("数据添加失败");

            }





        }

        $this->assign([

            'pid'=>$pid,

        ]);



        return $this->view->fetch();

    }



    /**

     * 2020/08/09

     * 景点添加视频

     * 王超

     */

    public function index_add_video(){

        $id = input("get.id");

        $this->assign(['id'=>$id]);

        return $this->view->fetch();

    }

    public function uploadAjax(){

        // 获取表单上传文件 例如上传了001.jpg

        $product_info_img=db("product_info_img");

        $id = input("post.id");

        $file = request()->file('image');

        $test=request()->post("test");

        $src=[];//返回文件路径

        $vdieo_src= "";//返回文件路径

        // 移动到框架应用根目录/public/uploads/ 目录下

        if($file){

            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');

            if($info){

                // 成功上传后 获取上传信息

                // 输出 jpg

                 $info->getExtension();

                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg

                 $info->getSaveName();

                // 输出 42a79759f284b767dfcb2a0197904287.jpg

                 $info->getFilename();

                 $src["src"] = DS.'public'.DS.'uploads'.DS.$info->getSaveName();

                 $vdieo_src = DS.'uploads'.DS.$info->getSaveName();



                 $data["id"] = $id;

                 $data["videourl"] = $vdieo_src;

                 db("route_info_img")->update($data);

                

            }else{

                // 上传失败获取错误信息

                 $file->getError();

            }

        };





        return json_encode($src);

    }



    /**

     * 删除视频

     */

    public function del_video(){

        $route_info_img=db("route_info_img");

        $id=input("id");

        $res=$route_info_img->find($id);

        $thumb_img_url=ROOT_PATH . 'public'."/".$res['videourl'];//查找文件

        $data["id"] = $id;

        $data["videourl"] = "";



        $result=$route_info_img->update($data);

        if($result){

            @unlink($thumb_img_url);//删除文件

            echo 1;

        }else{

            echo 0;

        }



    }











    /**

     *产品信息添加

     * 田博--190826

     */



    public function info_add(){

        $pid=input("pid");

        $fid=input("fid");

        $res=db("product_info")->where("id",$fid)->find();

        $info_type=getArr('product-info-type');

        if(request()->isPost()){

            $data=input("post.");

            $data['p_id']=$pid;

            $data['fid']=$fid;

            if($res){

                $data['info_type']=$res['info_type'];

            }

            $add=db("product_info")->insert($data);

            if($add){

                $this->success("信息添加成功","/admin/product/info_index?p_id={$pid}");

            }else{

                $this->error("信息添加失败");

            }

        }

        $this->assign([

            'pid'=>$pid,

            'res'=>$res,

            'info_type'=>$info_type,

        ]);

        return $this->view->fetch();

    }



    /**

     *产品信息修改

     * 田博--190826

     */



    public function info_edit(){

        $id=input("id");

        $info_type=getArr('product-info-type');

        $info=db("product_info");

        $res=$info->find($id);

        if(request()->isPost()){

            $data=input("post.");

            $update=$info->update($data);

            if($update){

                $this->success("数据修改成功","/admin/product/info_index?p_id={$res['p_id']}");

            }else{

                $this->error("数据修改失败") ;

            }



        }



        $this->assign([

            'res'=>$res,

            'info_type'=>$info_type,

        ]);

        return $this->view->fetch();

    }



    /**

     *产品信息状态修改

     * 田博--190826

     */

    public function changeStatus(){

        $id=input("id");

        $info=db("product_info");

        $res=$info->field("status")->find($id);

        if($res['status']==0){

            $info->where("id",$id)->setField("status",1);

            echo 1;//显示变隐藏

        }else{

            $info->where("id",$id)->setField("status",0);

            echo 2;//隐藏便显示

        }

    }

    /**

     *产品图片列表

     * 田博--190826

     */

    public function index_img(){

        $pid=input("id");

        $list=db("product_adimg")->where("p_id",$pid)->order("i_order desc")->select();

        if(request()->isPost()){

            $data=input("post.");

            foreach ($data as $k=>$v){

                db("product_adimg")->where("id",$k)->setField("i_order",$v);

            }

            $this->success("排序成功");

        }



        $this->assign([

            'pid'=>$pid,

            'list'=>$list

        ]);



        return $this->view->fetch();

    }



    /**

     *产品图片主图设置

     * 田博--190826

     */

    public function changeImg(){

        $img=db("product_adimg");

        $id=input("id");

        $pid=input("pid");

        $where['ismain']=array('eq',1);

        $where['p_id']=array("eq",$pid);

        $ismain=$img->where($where)->find();

        if($ismain['id']){

            $img->where("id",$ismain['id'])->setField("ismain",0);

        }

        $res=$img->where("id",$id)->setField("ismain",1);

        if($res){

            $result=$img->find($id);

            $result['imgurl'];

            db("product")->where("id=".$pid)->update(['proimg'=>$result['imgurl']]);

            echo 1;

        }else{

            echo 0;

        }



    }



    /**

     *产品图片删除

     * 田博--190826

     */

    public function index_del_img(){

        $id=input("id");

        $res=db("product_adimg")->find($id);

        if($res['imgurl']!=''){

            $filePaths = ROOT_PATH . 'public';

            $url=$filePaths.$res['imgurl'];

        }

        $del=db("product_adimg")->delete($id);

        if($del){

            unlink($url);

            $this->success("数据删除成功");

        }else{

            $this->error("数据删除失败");

        }

    }

    /**

     *产品图片修改

     * 田博--190826

     */

    public function index_edit_img(){

        $id=input("id");

        $res=db("product_adimg")->find($id);

        if(request()->isPost()){

            $data=input("post.");

            if($data['imgurl']!=''){

                //dump(preg_match("/upload/i",$data['imgurl']));

                if(preg_match("/upload/i",$data['imgurl'])){

                    $data['imgurl']=$res['imgurl'];

                }else{

                    if($res['imgurl']!=''){

                        $img_url=ROOT_PATH . 'public'.$res['imgurl'];

                        @unlink($img_url);

                    }

                    $img=base64_image_content($data['imgurl']);

                    $data['imgurl']=$img['url'];

                }

            }else{

                if($res['imgurl']!=''){

                    $img_url=ROOT_PATH . 'public'.$res['imgurl'];

                    @unlink($img_url);

                }

                $data['imgurl']='';

            }

            $add=db("product_adimg")->update($data);

            if($res['ismain']==1){



                db("product")->where("id",$res['p_id'])->update(['proimg'=>$data['imgurl']]);



            }







            if($add){

                $this->success("数据修改成功","/admin/product/index_img?id={$res['p_id']}");

            }else{

                $this->error("数据修改失败");

            }

        }



        $this->assign([

            'res'=>$res,

        ]);

        return $this->view->fetch();

    }



    /**

     *产品信息删除

     * 田博--190826

     */

    public function info_del(){

        $info=db("product_info");

        $product_info_img=db("product_info_img");

        $id=input("id");

        $arrSon=$this->getProductSon($id);

        array_unshift($arrSon,intval($id));

        // dump($arrSon);//die;

        foreach ($arrSon as $k=>$v){

            //dump($v);//die;

            $list=$product_info_img->where("pi_id",$v)->select();

            if($list){

                foreach ($list as $k1=>$v1){

                    $imgUrl=ROOT_PATH . 'public'.$v1['imgurl'];

                    @unlink($imgUrl);

                    $product_info_img->delete($v1['id']);

                }

                $info->delete($v);

            }else{

                $info->delete($v);

            }

        }

        $this->success("数据删除成功");



        /* if($res){

             $this->success("数据删除成功");

         }else{

             $this->error("数据删除失败");

         }*/

    }

    /**

     *查询产品信息的子节点

     * 田博--190912

     */

    public function getProductSon($fid){

        // dump($id);die;

        $info=db("product_info");

        $list=$info->select();

        return  $this->getProductSonSonAll($list,$fid);

    }

    /**

     *查询产品信息的子节点

     * 田博--190912

     */

    public function getProductSonSonAll($data,$fid){

        static $arr=array();

        foreach ($data as $k=>$v){

            if($fid==$v['fid']){

                $arr[]=$v['id'];

                $this->getProductSonSonAll($data,$v['id']);

            }

        }

        return $arr;

    }



    //产品关联推荐产品==产品选择

    function index_linkp(){

        $pid=input("pid");

        $status=getArr("product-status");

        $product_type=getArr("product-p_type");

        if(input("type") && input("id")==''&& input("p_no")==''  ){

            $where['p_type']=input("type");

            $search['p_type']=input("type");

        }else{

            $where['p_type']=array("in",'1,2,3,4');

            $search['p_type']=100;

        }

        if(input("id")!='' && input("id") >0 ){

            $where['id']=input("id");

            $search['id']=input("id");

            $search['p_type']='';

        }else{

            $search['id']='';

        }

        if(input("p_no") !='' && input("id")==''){

            $where['p_no']=array("like","%".input("p_no")."%");

            $search['p_no']=input("p_no");

            $search['p_type']='';

        }else{

            $search['p_no']='';

        }

        if(input("p_day") !='' && input("id")=='' && input("p_no")==''){

            $where['p_day']=input("p_day");

            $search['p_day']=input("p_day");

            $search['p_type']='';

        }else{

            $search['p_day']='';

        }

        if(input("status")!='' && input("id")=='' && input("p_no")==''){

            $where['status']=input("status");

            $search['status']=input("status");

            $search['p_type']='';

        }else{

            $search['status']=100;

        }

        if(input("p_name")!='' && input("id")=='' && input("p_no")==''){

            $p_name=input("p_name");

            $where['p_name']=array("like","%".$p_name ."%");

            $search['p_name']=input("p_name");

            $search['p_type']='';

        }else{

            $search['p_name']='';

        }



        // dump($where);

        // dump($search);

        $list=db("product")->where($where)->order("id desc")->paginate(10,false,['query'=>request()->param()]);

        $status1=getArr("product-status");

        // dump($search);

        $list=db("product")->where($where)->order("id desc")->paginate(30,false,['query'=>request()->param()]);

        $this->view->assign([

            "list"=>$list,

            'status1'=>$status1,

            'search'=>$search,

            'pid'=>$pid,

            'status'=>$status1,

            'product_type'=>$product_type,



        ]);





        $type = config('config.mark-type');

        $this->view->assign("type",$type);

        $this->view->assign("search",$search);

        return $this->view->fetch();

    }



       //产品关联推荐产品

       function index_product_link(){



           $pid=input("pid");

           $action=input("action");

           $delid=input("delid");

           $addid=input("addid");

           $senseid=input("senseid");





           if($action=="del"){

               db("ad")->delete($delid);

              $adnum= db("ad")->where("sense_id=".$senseid)->count();

              if($adnum==0){

                  db("adsense")->delete($senseid);

              }



           }



           //判断该产品是否有广告位(推荐)，若没有则添加广告位后加入信息，若有则直接加入产品

           if($action=="add"){



               $adsense=db("adsense")->where("adtype=1 and p_id=".$pid)->find();

               if($adsense){

                   $adinfo=[];

                   $adinfo["p_id"]=$addid;

                   $adinfo["sense_id"]=$adsense['id'];

                   db("ad")->insert($adinfo);

               }else{



                   $adsenseinfo=[];

                   $adsenseinfo['adtype']=1;

                   $adsenseinfo['p_id']=$pid;

                   $adsenseid=db("adsense")->insertGetId($adsenseinfo);

                   $adinfo=[];

                   $adinfo["p_id"]=$addid;

                   $adinfo["sense_id"]=$adsenseid;

                   db("ad")->insert($adinfo);



               }

           }







           $adsense=db("adsense")->where("adtype=1 and p_id=".$pid)->find();

          $adplist=[];

           if($adsense){

               $adlists=db("ad")->where("sense_id=".$adsense['id'])->order("ad_order desc")->select();

              for($i=0;$i<count($adlists);$i++){

                  $adpinfo=db("product")->where("id=".$adlists[$i]["p_id"])->find();

                  $adpinfo["adid"]=$adlists[$i]["id"];

                  $adpinfo["ad_order"]=$adlists[$i]["ad_order"];

                  $adpinfo["senseid"]=$adlists[$i]["sense_id"];

                  $adplist[]=$adpinfo;

              }

           }

           $this->view->assign("adplist",$adplist);

           $this->view->assign("pid",$pid);

           return $this->view->fetch();

       }



    /**

     *修改产品标签

     * 主要功能根据已有的产品ID 查找、添加与其相关联的标签

     * 田博--190826

     */

    public function index_mark(){

        $pid=input("id");

        $mark=db("mark");

        $mark_type=input("get.type");

        // dump($mark_type);

        if($mark_type==0){

            $where['mark_type']=array("in","0,2,3,4,1,5,6,7,8,9");

            $search=0;

        }else{

            $where['mark_type']=$mark_type;

            $search=$mark_type;

        }

        $list=$mark->where($where)->order("id desc")->paginate(15,false,['query'=>request()->param()]);

        ///dump($list);



        $this->assign([

            'list'=>$list,

            'pid'=>$pid

        ]);

        $type = config('config.mark-type');

        $this->view->assign("type",$type);

        $this->view->assign("search",$search);

        return $this->view->fetch();



    }

    /**

     *添加产品标签

     * 田博--190826

     */



    public function markAdd(){

        $mark=db("mark");

        $product_info=db("product_mark");

        if(request()->isAjax()){

            $pid=input("pid");

            $flag=input("flag");

            if($flag){

                $id=input("id");

                $where['mark_id']=$id;

                $where['p_id']=$pid;

                $info=db("product_mark")->where($where)->find();

                if($info['id']){

                    echo 2;die;

                }

                $res=$mark->find($id);

                $data['mark_id']=$id;

                $data['mark_info']=$res['mark_info'];

                $data['mark_type']=$res['mark_type'];

                $data['isself']=0;

            }else{

                $info=db("product_mark")->where("mark_info",input("info"))->find();

                if($info['id']){

                    echo 2;die;

                }

                $data['mark_info']=input("info");

                $data['mark_id']='';

                $data['isself']=1;

                $data['mark_type']=12;

            }

            $data['p_id']=$pid;

            $data['senec']=1;

            $data['stylename']=1;

            $result=$product_info->insert($data);

            if($result){

                echo 1;

            }else{

                echo 0;

            }

        }else{

            $this->error("非法请求");

        }

    }





    /**

     *已选的标签

     * 田博--190826

     */



    public function index_product_mark(){

        $product_info=db("product_mark");

        $pid=input("pid");

        $mark_type=input("get.type");





        if(request()->isPost()){

            $data=input('post.');

            foreach ($data['senec'] as $k=>$v){

                $product_info->where("id",$k)->setField("senec",$v);

            }

            foreach ($data['stylename'] as $k=>$v){

                $product_info->where("id",$k)->setField("stylename",$v);

            }

            foreach ($data['m_order'] as $k=>$v){

                $product_info->where("id",$k)->setField("m_order",$v);

            }

            $this->redirect("/admin/product/index_product_mark?pid={$pid}&type={$mark_type}");

        }



        //$senec=config("config.product-senec");

        $senec=getArr("product-senec");

        $stylename=getArr("product-stylename");



        $type = config('config.mark-type');

        $this->view->assign("type",$type);

        if($mark_type==0 || $mark_type==""){

            //$where_mark['mark_type']=array("in","0,1,2,3,4,5,6,7,8,9");

            $search=0;

        }else{

            $where_mark['mark_type']=$mark_type;

            $search=$mark_type;

        }



        $where_mark['p_id']=$pid;

        ///dump($where_mark);



        $list=$product_info->where($where_mark)->order("m_order desc")->select();



        $this->assign([

            "list"=>$list,

            "pid"=>$pid,

            "senec"=>$senec,

            "stylename"=>$stylename,

            'search'=>$search,

        ]);



        return $this->view->fetch();

    }



    /**

     *删除已选的标签

     * 田博--190826

     */



    public function product_save_del(){

        $pid=input("pid");

        $id=input("id");

        $where['p_id']=$pid;

        $where['id']=$id;

        $res=db("product_mark")->where($where)->delete();

        if($res){

            echo 1;

        }else{

            echo 0;

        }







    }



    /**

     *一键生成关联路线

     * 主要功能根据已有productid，完全复制一个新的产品，包括所有子表及图片

     * 需要复制  1-主表 2-产品广告图表 3-天数详情表（包括详情子表） 4-团期价格表（包括价格表） 5-产品标签表 6-产品优惠券表

     * javen-190820

     */

    public function link_copy(){



        //获取产品id,复制主表

        $p_id=input("p_id");



        $pro1=db("product")->find($p_id);

        $pro1['id']="";

        $pro1insert=db("product")->insertGetId($pro1);



        //复制主表结束



        //根据主表复制 产品info--  product_info

        $pro1info=db("product_info")->where("p_id=".$p_id)->select();

        foreach($pro1info as $k =>$v) {

            $v["id"]="";

            $v["p_id"]=$pro1insert;

            db("product_info")->insertGetId($v);

        }

        //根据主表复制 产品图片--  product_adimg

        $pro1adimg=db("product_adimg")->where("p_id=".$p_id)->select();

        foreach($pro1adimg as $k =>$v) {

            $v["id"]="";

            $v["p_id"]=$pro1insert;

            //图片复制--构造新的路径文件名

            $ipath=str_replace('/uploads/','uploads/',$v["imgurl"]);

            $ipathto=str_replace('.','b.',$ipath);

            $v["imgurl"]='/'.$ipathto;



            if(file_exists($ipath)){

                copy($ipath,$ipathto);

            };

            db("product_adimg")->insertGetId($v);

        }



        //根据主表复制天数详情  route

        $pro1route=db("route")->where("p_id=".$p_id)->select();

        foreach($pro1route as $k =>$v) {

            $tid=$v["id"];

            $v["id"]="";

            $v["p_id"]=$pro1insert;

            $routeid= db("route")->insertGetId($v);



            $pro1routeinfo=db("route_info")->where("tr_id=".$tid)->select();

            foreach($pro1routeinfo as $k1 =>$v1) {

                $trid=$v1["id"];

                $v1["id"]="";

                $v1["tr_id"]=$routeid;

                $routeinfoid=db("route_info")->insertGetId($v1);

                $pro1routeinfoimg=db("route_info_img")->where("tri_id=".$trid)->select();

                foreach($pro1routeinfoimg as $k2 =>$v2) {

                    $tri_id=$v2["id"];

                    $v2["id"]="";

                    $v2["tri_id"]=$routeinfoid;

                    //图片复制--构造新的路径文件名

                    $ipath=str_replace('/uploads/','uploads/',$v2["imgadr"]);

                    $ipathto=str_replace('.','b.',$ipath);

                    $v2["imgadr"]='/'.$ipathto;

                    if(file_exists($ipath)){

                        copy($ipath,$ipathto);

                    };

                    db("route_info_img")->insertGetId($v2);

                }

            }

        }







        //根据主表g_p_type  复制团期及价格  product_group或者product_group_b





        //g_p_type==1

        if($pro1['g_p_type']==1){



            $pro1group=db("product_group")->where("p_id=".$p_id)->select();

            foreach($pro1group as $k =>$v) {

                $gid=$v["id"];

                $v["id"]="";

                $v["p_id"]=$pro1insert;

                $ginsertid= db("product_group")->insertGetId($v);

                $pro1gprice1=db("product_price_a")->where("group_id=".$gid)->select();

                foreach($pro1gprice1 as $k1 =>$v1) {

                    $v1["id"]="";

                    $v1["p_id"]=$pro1insert;

                    $v1["group_id"]=$ginsertid;

                    $ginsertid= db("product_price_a")->insertGetId($v1);

                }





            }

        }

        //g_p_type==2

        if($pro1['g_p_type']==2){



            $pro1groupb=db("product_group_b")->where("p_id=".$p_id)->select();

            foreach($pro1groupb as $k =>$v) {

                $gbid=$v["id"];

                $v["id"]="";

                $v["p_id"]=$pro1insert;

                $gbinsertid= db("product_group_b")->insertGetId($v);

                $pro1gprice1=db("product_price_b")->where("group_b_id=".$gbid)->select();

                foreach($pro1gprice1 as $k1 =>$v1) {

                    $v1["id"]="";

                    $v1["p_id"]=$pro1insert;

                    $v1["group_b_id"]=$gbinsertid;

                    $ginsertid= db("product_price_b")->insertGetId($v1);

                }

            }



        }



        //根据主表  复制标签 product_mark

        $pro1mark=db("product_mark")->where("p_id=".$p_id)->select();

        foreach($pro1mark as $k =>$v) {

            $mid=$v["id"];

            $v["id"]="";

            $v["p_id"]=$pro1insert;

            $ginsertid= db("product_mark")->insertGetId($v);

        }



        //根据主表  复制优惠券信息 coupon_product



        $pro1coupon=db("coupon_product")->where("product_id=".$p_id)->select();

        foreach($pro1coupon as $k =>$v) {

            $cid=$v["id"];

            $v["id"]="";

            $v["product_id"]=$pro1insert;

            $ginsertid= db("coupon_product")->insertGetId($v);

        }

        $this->redirect('/admin/product/index');

    }

    /**

     *根据旧网站pid 生成新网站产品数据

     *

     *



     */

    public function product_oldinput(){



        $pid=input("p_id");







        //1.首先判断是否已经导入过

        $temp1=db("temp")->where("id1=".$pid)->find();



        if($temp1!=""){

            //已经导入过了;

             $this->error("已经导入,新网站产品id----".$temp1["id2"]);

            return;

        }



        //2.判断 旧网站数据库中产品是否存在

        $product = db::connect('db2')->table('xdnet_product')->where("id=".$pid)->find();



        if($product==""){

            //未查找到记录;

            $this->error("输入的id有误，请重新输入");

            return;

        }

        if(!($product['catid']==12||$product['catid']==4)){



            //只能导入拼团游和包团游;

            $this->error("只能导入拼团游和包团游");

            return;

        }







        //3.生成主表内容





       //获取产品编号字符

        $pnoe=db("num")->field('pno')->where("id=1")->find();

        db("num")->where('id=1')->setInc('pno');



        $pnoe=(int)$pnoe['pno']+1;

        $product1=[

            "p_name"=>$product['xlmc'],

            "s_name"=>$product['title'],

            "e_name"=>$product['showtitle'],

            "p_no"=>"TOUR-".$pid,

            "status"=>0,

            "transport"=>$product['jtfs'],

        ];

        if($product['catid']==12){

            $product1['p_type']=1;

            $product1['pricetype']=1;



        }

        if($product['catid']==4){

            $product1['p_type']=2;

            $product1['pricetype']=1;

        }



        $productid= db("product")->insertGetId($product1);

        $temp1=[

            "id1"=>$product['id'],

            "name1"=>$product['xlmc'],

            "id2"=>$productid,

            "ctime"=>time(),

            "userid"=>$_SESSION['think']['admin']['id'],

            "username"=>$_SESSION['think']['admin']['username']

        ];

        db("temp")->insertGetId($temp1);



        //增加默认套餐组

        $data= ['p_id' => $productid,

            'fid' => 0,

            'pptype' => 0,

            'ptitle' => '默认线路(套餐)总类别',

            'status'=>1,

            'pa_order'=>1,

            'pricetype'=>1,



        ];



        Db::name('product_package')->insert($data);

        $paid = Db::name('product_package')->getLastInsID();

        $data= ['p_id' => $productid,

            'fid' => $paid,

            'pptype' => 1,

            'ptitle' => '默认线路(套餐)组',

            'status'=>1,

            'pa_order'=>1,

            'pricetype'=>1,

            'selecttype'=>2,

        ];



        Db::name('product_package')->insert($data);

        $paid1 = Db::name('product_package')->getLastInsID();



        $data= ['p_id' => $productid,

            'fid' => $paid1,

            'pptype' => 2,

            'ptitle' => '默认线路(套餐)',

            'status'=>1,

            'pa_order'=>1,

            'selecttype'=>2,

            'pricetype'=>1,

            'pa_showchar'=>"A",

        ];

        $packageid=Db::name('product_package')->insertGetId($data);





        //4.生成团期及价格---两种模式 1--拼团游 2--包团游

        //定义产品最低价

        $productlowprice=10000000;

        //定义产品需要显示的折扣

        $productdiscount=0;

        //拼团游团期

        if($product['catid']==12){

            $pg1 = db::connect('db2')->table('xdnet_product_tq')->where("fid=".$product['id'])->select();



            for($i=0;$i<count($pg1);$i++){



                //定义当前团期最低价

                $grouplowprice=10000000;

                //计算单人房差，若没有一人价，将二人价分为一人价和单人房差

                $onehouse="";

                $price1arr=explode("|", $pg1[$i]['price']);

                if(!is_numeric($price1arr[0])) {

                    $price1arr[0]=$price1arr[1];

                }

                $onehouse= round($price1arr[0]-$price1arr[1]/2);

                $price1arr[0]=$price1arr[0]-$onehouse;



                if(count($price1arr)==5){

                    unset($price1arr[4]);

                    unset($price1arr[3]);

                }





                if((!isset($pg1[$i]['zk']))||$pg1[$i]['zk']==""){

                    $pg1[$i]['zk']=0;

                }



                for($j=0;$j<count($price1arr);$j++){

                    $price1arr[$j]=round($price1arr[$j]/($j+1));

                    //判断团期最低单价

                    if(($price1arr[$j]-($price1arr[$j]*($pg1[$i]['zk']/100)))<$grouplowprice){

                        $grouplowprice=$price1arr[$j]-($price1arr[$j]*($pg1[$i]['zk']/100));

                    }

                    //判断产品最低单价

                    if(($price1arr[$j]-($price1arr[$j]*($pg1[$i]['zk']/100)))<$productlowprice){

                        $productlowprice=($price1arr[$j]-($price1arr[$j]*($pg1[$i]['zk']/100)));

                    }

                }

                //判断产品显示折扣

                if($pg1[$i]['zk']>$productdiscount){

                    $productdiscount=$pg1[$i]['zk'];

                }

                $group1=[

                    "p_id"=>$productid,

                    "g_max"=>10,

                    "g_time"=>$pg1[$i]['tq'],

                    "discount"=>$pg1[$i]['zk'],

                    "onehouse"=>$onehouse,

                    "price"=>$grouplowprice,

                    "discounttype"=>$pg1[$i]['type'],

                    "industry_share"=>$pg1[$i]['toty'],

                    "housetype"=>count($price1arr),

                    "info"=>$pg1[$i]['title'],

                    "package_id"=>$packageid

                ];

                $group1id= db("product_group")->insertGetId($group1);



                for($j=0;$j<count($price1arr);$j++){

                    $price1a=[

                        "p_id"=>$productid,

                        "group_id"=>$group1id,

                        "p_num"=>$j+1,

                        "price"=>$price1arr[$j],

                        "title"=>($j+1)."人",

                        "package_id"=>$packageid

                    ];

                    if($j==0){

                        $price1a['info']="单人价包含".$onehouse."欧元《单人房差》押金，拼房成功立刻退还";

                    }

                    if($j==1){

                        $price1a['info']="两人入住标准双人间大床或双床房";

                    }

                    if($j==2){

                        $price1a['info']="三人同行入住三人间";

                    }

                    db("product_price_a")->insertGetId($price1a);



                }



                $this->model->getgpest($group1id);



            }



            $this->model->getpriceest($productid);

        }



        //包团游团期

        if($product['catid']==4) {



            //包团游不导入团期价格体系，后期生成

        }

        //5.生成产品行程

        $product_route = db::connect('db2')->table('xdnet_product_day')->where("fid=".$pid)->order("listorder")->select();



        db("product")->where('id', $productid)->update(['p_day' => count($product_route)]);

        for($i=0;$i<count($product_route);$i++){

            $route=[

                "p_id"=>$productid,

                "day_no"=>$product_route[$i]['listorder'],

                "titlearr"=>$product_route[$i]['title'],

                "package_id"=>$packageid

            ];

            $routeid= db("route")->insertGetId($route);



            $titlearr=[

                "tr_id" => $routeid,

                "itype" => "1",

                "title" => getstr("route_info-itype",1),

                "info" => $product_route[$i]['xcgs'],

                "tagid" => 1,

            ];

            Db::name('route_info')->insert($titlearr);



            $titlearr=[

                "tr_id" => $routeid,

                "itype" => "3",

                "title" => getstr("route_info-itype",3),

                "info" => $product_route[$i]['zhus']."<br/>".$product_route[$i]['zhusjs'],

                "tagid" => 3,

            ];

            Db::name('route_info')->insert($titlearr);



            $titlearr=[

                "tr_id" => $routeid,

                "itype" => "5",

                "title" => getstr("route_info-itype",5),

                "info" => $product_route[$i]['xcgl'],

                "tagid" => 5,

            ];

            Db::name('route_info')->insert($titlearr);



        }





        set_route_day($productid,$packageid);









        //6.生成产品信息



        //行程高亮---导入产品特色

        $info1=[

            "p_id"=>$productid,

            "info_type"=>1,

            "title"=>"产品特色",

            "info"=>"<pre>".$product['xcgl']."</pre>",

            "fid"=>0,

            "status"=>0,

            "info_order"=>1

        ];

        $info1id= Db::name('product_info')->insertGetId($info1);



        //产品高亮图片--导入产品特色



        $pimgstr=$product['glpic'];



        preg_match_all("<img.*?src=\"(.*?.*?)\".*?>",$pimgstr,$match); //这里是关键



        for($iinfo=0;$iinfo<count($match[1]);$iinfo++){

            $infoimgurl="";

            if(substr($match[1][$iinfo] , 0 , 4)=="http"){

                $infoimgurl= $match[1][$iinfo];

            }else{

                $infoimgurl="http://www.paris-girafe.com/".$match[1][$iinfo];

            }







            echo $infoimgurl;

            echo "<img src='".$infoimgurl."'/>";

            echo "<br/>";

            $imgpath=$this->GrabImage($infoimgurl,"","","");

            $infoimg=[

                "pi_id"=>$info1id,

                "imgurl"=>$imgpath,

                "i_order"=>$iinfo,

            ];

            Db::name('product_info_img')->insertGetId($infoimg);

        }

        //---导入费用说明

        $info2=[

            "p_id"=>$productid,

            "info_type"=>2,

            "title"=>"费用说明",

            "fid"=>0,

            "status"=>0,

            "info_order"=>2

        ];

        $info2id= Db::name('product_info')->insertGetId($info2);

        $info21=[

            "p_id"=>$productid,

            "info_type"=>3,

            "title"=>"费用包含",

            "info"=>"<pre>".$product['fybh']."</pre>",

            "fid"=>$info2id,

            "info_order"=>1,

            "status"=>0

        ];

        Db::name('product_info')->insertGetId($info21);

        $info22=[

            "p_id"=>$productid,

            "info_type"=>4,

            "title"=>"费用不包含",

            "info"=>"<pre>".$product['fybbh']."</pre>",

            "fid"=>$info2id,

            "info_order"=>2,

            "status"=>0

        ];

        Db::name('product_info')->insertGetId($info22);

        //导入签证说明

        $info3=[

            "p_id"=>$productid,

            "info_type"=>5,

            "title"=>"签证说明",

            "info"=>"<pre>".$product['qzxz']."</pre>",

            "fid"=>0,

            "info_order"=>3,

            "status"=>0

        ];

        Db::name('product_info')->insertGetId($info3);

        //导入预定须知

        $info4=[

            "p_id"=>$productid,

            "info_type"=>6,

            "title"=>"预定须知",

            "fid"=>0,

            "info_order"=>4,

            "status"=>0

        ];

        $info4id= Db::name('product_info')->insertGetId($info4);



        // 导入常见问题

        $info41=[

            "p_id"=>$productid,

            "info_type"=>7,

            "title"=>"常见问题",

            "info"=>"<pre>".$product['cjwt']."</pre>",

            "fid"=>$info4id,

            "info_order"=>1,

            "status"=>0

        ];

        Db::name('product_info')->insertGetId($info41);

        // 导入购买须知

        $info42=[

            "p_id"=>$productid,

            "info_type"=>8,

            "title"=>"购买须知",

            "info"=>"<pre>".$product['zysx']."</pre>",

            "fid"=>$info4id,

            "info_order"=>2,

            "status"=>0

        ];

        Db::name('product_info')->insertGetId($info42);



        // 导入安全须知

        $info43=[

            "p_id"=>$productid,

            "info_type"=>9,

            "title"=>"安全须知",

            "info"=>"<pre>".$product['aqxz']."</pre>",

            "fid"=>$info4id,

            "info_order"=>3,

            "status"=>0

        ];

        Db::name('product_info')->insertGetId($info43);

        //7.生成产品主图

        $productpicarr = db::connect('db2')->table('xdnet_product_day_pic')->where("pid=".$pid." and isbanner=1")->select();



        for($i=0;$i<count($productpicarr);$i++){



            $imgurl="http://www.paris-girafe.com".$productpicarr[$i]['pic'];



            echo $imgurl."<br/>";



            $imgpath= $this->GrabImage($imgurl,"",510,320);



            $pimgarr=[

                "p_id"=>$productid,

                "imgurl"=>$imgpath,

                "title"=>$productpicarr[$i]['title'],

                "title2"=>$product['title'],

            ];

            Db::name('product_adimg')->insertGetId($pimgarr);



        }



        $productpicurl="http://www.paris-girafe.com".$product['thumb'];

        $imgpath=$this->GrabImage($productpicurl,"",510,320);

        $pimgarr=[

            "p_id"=>$productid,

            "imgurl"=>$imgpath,

            "title"=>$product['title'],

            "title2"=>$product['title'],

            "ismain"=>1,

        ];

        Db::name('product_adimg')->insertGetId($pimgarr);







    }





    /**javen

    将远程服务器上的图片存储到当前服务器上--

     * filename为空，返回文件名包含全路径  不包含https

     *  $w,$h 生成图片宽高，为空则不处理

     **/

    function GrabImage($url, $filename = "",$w,$h) {

        if ($url == ""):return false;

        endif;

        //如果$url地址为空，直接退出

        if ($filename == "") {

            //如果没有指定新的文件名

            $ext = strrchr($url, ".");

            //得到$url的图片格式

            if ($ext != ".gif" && $ext != ".jpg"&& $ext != ".png"&& $ext != ".jpeg"):return false;

            endif;

            //如果图片格式不为.gif或者.jpg，直接退出



            $fpath1=date("Ymd",time());

            $filePaths = ROOT_PATH . 'public' . DS . 'uploads' . DS .$fpath1. DS ;

            if(!file_exists($filePaths)){

                mkdir($filePaths,0777,true);

            }

            $fpath3=$this->getRandomString(15);

            $fpath2=$fpath1. DS .$fpath3.$ext;

            $filename = $filePaths.$fpath3.$ext;

            //用天月面时分秒来命名新的文件名

        }

        ob_start();//打开输出

        readfile($url);//输出图片文件

        $img = ob_get_contents();//得到浏览器输出

        ob_end_clean();//清除输出并关闭

        $size = strlen($img);//得到图片大小

        $fp2 = @fopen($filename, "a");

        fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名

        fclose($fp2);

        $image = \think\Image::open($filename);

        if($w==""){

            $w=$image->width();

        }

        if($h==""){

            $h=$image->height();

        }

        $image->thumb($w,$h,6)->save($filename);

        return "/uploads/".$fpath2;//返回新的文件名

    }



    /**

     * 获取随机字符串

     * @param int $len 字符串长度

     * @param string $chars 字符源

     * @return string

     */

    function getRandomString($len, $chars = null)

    {

        if (is_null($chars))

            $chars = "abcdefghijklmnopqrstuvwxyz0123456789";

        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {

            $str .= $chars[mt_rand(0, $lc)];

        }

        return $str;

    }

    

    /**

    2020/7/21何国红包团

     **/

    public function package_tour(){

        //调用淡旺季设置内容

        $type = config('config.season-ptype');

        $this->view->assign("type", $type);

        $p_id = input("get.p_id");

        $package_id = input("get.package_id");

        if($p_id && $package_id){

            $product = $this->model->where("id=".$p_id)->find();

            $tour = db('product_tour')->where("package_id=".$package_id)->find();

            $map['package_id']= $package_id;

            $map['p_id']= $p_id;

            $map['group_id']= $tour['id'];

            $tourprice = db('product_tour_price')->where($map)->select();

            $this->view->assign("package_id", $package_id);

            $this->view->assign("product", $product);

            $this->view->assign("tour", $tour);

            $this->view->assign("tourprice", $tourprice);

            $this->view->assign("p_id", $p_id);

            

        }else{

            $this->error("产品ID有误！");

        }

        return $this->view->fetch();

    }



    public function package_tour_del(){

        //调用淡旺季设置内容

        $p_id = input("get.p_id");

        $package_id = input("get.package_id");

        if($p_id && $package_id){

            $tour = db('product_tour')->where("package_id=".$package_id)->find();

            if($tour){

            $delwhere['p_id'] = $p_id;

            $delwhere['package_id'] = $package_id;

            $tourdel = db('product_tour')->where($delwhere)->delete();

            if($tourdel){

               $tour = db('product_tour_price')->where($delwhere)->delete();

               $this->success("团期删除成功！",url("/admin/product/group_package?pid=".$p_id."&p_type=2"));   

            }

        } else{

            $this->error("还没有添加团期，不能删除");

        }

        }else{

            $this->error("产品ID有误！");

        }

    }





    /**

    设置包团游价格

     **/

    public function package_group_price(){



        $package_id = input("post.package_id");

        $p_id = input("post.p_id");

        $id = input("post.id");//产品id

        $data["p_id"] = $p_id;//产品id

        $discount = input("post.discount");//折扣

        $data["package_id"] = $package_id;//套餐id

        $data["discount"] = $discount;//折扣

        $data["industry_share"] = input("post.industry_share");//同业是否享受官网折扣

        $data["discounttype"] = input("post.discounttype");//折扣类型 0-早鸟 1-闪电促销

        $data["start_time"] = strtotime(input("post.start"));//团期开始时间

        $data["end_time"] = strtotime(input("post.end"));//团期结束时间

        $data["season_type"] = input("post.season_type");

        $data_price1 = [];



        $tour = db('product_tour')->where("package_id=".$package_id)->find();

        $map['package_id']= $package_id;

        $map['p_id']= $p_id;

        $map['group_id']= $tour['id'];

        $tourprice = db('product_tour_price')->where($map)->select();

        

        if($tour && $tourprice){

            $tourupd = db('product_tour')->where("id=".$id)->update($data);

        

        }else{

            $tour_id = db('product_tour')->insertGetId($data); 

        }

    

        //封装价格数组，用于在插入数据库时不需要重新获取数据

        $w_length = count($_POST['w_season']);

        for ($i=0;$i<$w_length;$i++){

            if(!$tour && !$tourprice){

                $data_price1[$i]["group_id"] = $tour_id;

                $data_price1[$i]["p_id"] = $p_id;

                $data_price1[$i]["package_id"] = $package_id;

            }

            $data_price1[$i]["season"] = $_POST['w_season'][$i];

            $data_price1[$i]["tow_num"] = $_POST['tow_num'][$i];

            $data_price1[$i]["three_num"] = $_POST['three_num'][$i];

            $data_price1[$i]["four_num"] = $_POST['four_num'][$i];

            $data_price1[$i]["five_num"] = $_POST['five_num'][$i];

            $data_price1[$i]["six_num"] = $_POST['six_num'][$i];

            $data_price1[$i]["seven_num"] = $_POST['seven_num'][$i];

            $data_price1[$i]["tow_info"] = $_POST['tow_info'][$i];

            $data_price1[$i]["three_info"] = $_POST['three_info'][$i];

            $data_price1[$i]["four_info"] = $_POST['four_info'][$i];

            $data_price1[$i]["five_info"] = $_POST['five_info'][$i];

            $data_price1[$i]["six_info"] = $_POST['six_info'][$i];

            $data_price1[$i]["seven_info"] = $_POST['seven_info'][$i];



           

            $datemin[$i]["tow_num"] = $_POST['tow_num'][$i];

            $datemin[$i]["three_num"] = $_POST['three_num'][$i];

            $datemin[$i]["four_num"] = $_POST['four_num'][$i];

            $datemin[$i]["five_num"] = $_POST['five_num'][$i];

            $datemin[$i]["six_num"] = $_POST['six_num'][$i];

            $datemin[$i]["seven_num"] = $_POST['seven_num'][$i];



        }

      

        //求最小值

        foreach($datemin as $key =>$ffsd){

            $group_tow[$key]['tow_num']=$ffsd['tow_num'];

            $group_three[$key]['three_num']=$ffsd['three_num'];

            $group_four[$key]['four_num']=$ffsd['four_num'];

            $group_five[$key]['five_num']=$ffsd['five_num'];

            $group_six[$key]['six_num']=$ffsd['six_num'];

            $group_seven[$key]['seven_num']=$ffsd['seven_num'];

        }

       

        $paixun = implode(min($group_tow)).'|'.implode(min($group_three)).'|'.implode(min($group_four)).'|'.implode(min($group_five)).'|'.implode(min($group_six)).'|'.implode(min($group_seven));

        $lowest_price = min(explode('|',$paixun));

      

        //删除私家团之前添加到product_group表的团期

        $groupselect = db('product_group')->where("p_id=".$p_id)->select();

        if($groupselect){

            foreach($groupselect as $kk=>$kkval){

                $delmap[$kk]['id']=$kkval['id']; 

            }

            for($i=0;$i<count($delmap);$i++){

                db('product_group')->delete($delmap[$i]['id']);

            }

        }



        if($tour && $tourprice){

            if($data_price1){ 

                foreach($tourprice as $keys => $val){

                    $tourpriceid[$keys]['id'] = $tourprice[$keys]['id'];

                }

                for ($i=0;$i<count($data_price1);$i++){   

                    db('product_tour_price')->where("id=".$tourpriceid[$i]['id'])->update($data_price1[$i]);

                }



            $disct['discount'] = input("post.discount");//折扣

            $disct['lowprice'] = round($lowest_price*((100-$discount)/100));

            $tourupd = db('product')->where("id=".$p_id)->update($disct);

            $this->success("团期修改成功！",url("/admin/product/group_package?pid=".$p_id."&p_type=2"));

            }

           

        }else{

            if($tour_id){

                if($data_price1){

                    for ($i=0;$i<count($data_price1);$i++){

                        db('product_tour_price')->insert($data_price1[$i]);    

                    }

                }

                $disct['discount'] = input("post.discount");//折扣

                $disct['lowprice'] = round($lowest_price*((100-$discount)/100));

                $tourupd = db('product')->where("id=".$p_id)->update($disct);

                $this->success("团期价格设置成功！",url("/admin/product/group_package?pid=".$p_id."&p_type=2"));

               

            }



        }





    }







    /**

    线路维护

     * 20190927  田博

     **/



    public function product_line(){

        $product_link=db("product_link");

        $pid=input("get.id");

        //dump($pid);

        $pro_res=db("product")->field("s_name")->find($pid);

        //当前产品下  同一linkno数据

        $res=$product_link->field("linkno,id")->where("p_id",$pid)->find();

        $list=$product_link->where("linkno",$res['linkno'])->order("l_order asc")->select();

        foreach($list as $k=>$v){

            $list[$k]['pro_name']=db("product")->field("s_name")->find($v['p_id']);

        }

        $count=count($list);

        // dump($list);



        //其他linkno 数据

        $where['linkno']=array("neq",$res['linkno']);

        $otherList=$product_link->field("linkno")->where($where)->group("linkno")->select();

        //dump($otherList);

        foreach ($otherList as $k=>$v){

            $otherList[$k]['other']=$product_link->where("linkno",$v['linkno'])->order("l_order asc")->select();

            //dump($otherList[$k]['other']);

            foreach ($otherList[$k]['other'] as $kk=>$vv){

                $otherList[$k]['other'][$kk]['pro_name']=db("product")->field("s_name")->find($vv['p_id']);

            }

        }

        if(request()->isPost()){

            $data=input("post.");

            //dump($data);

            foreach($data as $k=>$v){

                $product_link->where("id",$k)->setField("title",$v);

            }

            $this->success("数据修改成功");

        }

        //dump($otherList);

        $this->assign([

            'list'=>$list,

            'pid'=>$pid,

            'other'=>$otherList,

            'pro_res'=>$pro_res,

            'count'=>$count,

        ]);

        return $this->view->fetch();

    }

    /**

    线路维护 向上移动

     * 20191025  田博

     **/

    public function product_line_up(){

        if(Request()->isAjax()){

            //dump(input("get."));die;

            $product_link=db("product_link");

            $id=input("id");//当前ID

            $prev_id=input("prev_id");//上一个ID

            //dump();

            $id_line=$product_link->field("l_order")->find($id);

            $prev_line=$product_link->field("l_order")->find($prev_id);



            $res=$product_link->where("id",$id)->setField("l_order",$prev_line['l_order']);

            $res1=$product_link->where("id",$prev_id)->setField("l_order",$id_line['l_order']);

            if($res && $res1){

                echo 1;

            }else{

                echo 0;

            }

        }

    }

















    /**

    产品套餐列表

     * 20191104  田博

     **/





















    /**

    产品套餐添加

     * 20191104  田博

     **/









    //查询product_package 表中的所有数据

    public function getFatherAll($pid,$fid){

        // dump($id);

        $list=db("product_package")->field("*")->where("p_id",$pid)->select();

        $this->getFather($list,$fid);

    }



    //查询所有的父节点

    public function getFather($arr,$id){

        foreach($arr as $k =>$v) {

            if($v['id'] == $id) {

                $arr1=array();

                $arr1[]=$v['fid'];

                $arr1[]=$v['ptitle'];

                array_unshift($this->fatherArr,$arr1);//函数用于向数组插入新元素。新数组的值将被插入到数组的开头//使用数字键名 返回新数组

                $this->getFather($arr,$v['fid']);

            }

        }

    }



    /**

     *产品套餐状态修改

     * 田博--190826

     */

    public function changePackage(){

        $id=input("id");

        $package=db("product_package");

        $res=$package->field("status")->find($id);

        if($res['status']==1){

            $package->where("id",$id)->setField("status",2);

            echo 1;//显示变隐藏

        }else{

            $package->where("id",$id)->setField("status",1);

            echo 2;//隐藏便显示

        }

    }



    /**

    产品套餐修改

     * 20191104  田博

     **/









    /**

    产品套餐--向上移

     * 20191120  田博

     **/

    public function package_up(){

        if(request()->isAjax()){

            $id=input("post.id");

            $product_package=db("product_package");

            $res=$product_package->field("*")->where("id",$id)->find();

            $pa_order=$res['pa_order']-1;

            $prev=$product_package->field("*")->where(['p_id'=>$res['p_id'],'fid'=>$res['fid'],'status'=>1,'pptype'=>$res['pptype'],'pa_order'=>$pa_order])->find();

            $result=$product_package->where("id",$id)->setField("pa_order",$pa_order);

            $result1=$product_package->where("id",$prev['id'])->setField("pa_order",$res['pa_order']);

            if($result && $result1){

                ajaxMsg();

            }else{

                ajaxMsg("数据上移失败",0);

            }

        }

    }





    /**

    产品套餐--向下移

     * 20191120  田博

     **/

    public function package_down(){

        if(request()->isAjax()){

            $id=input("post.id");

            $product_package=db("product_package");

            $res=$product_package->field("*")->where("id",$id)->find();

            //dump($res);

            $pa_order=$res['pa_order']+1;

            // dump($pa_order);

            $next=$product_package->field("id")->where(['p_id'=>$res['p_id'],'fid'=>$res['fid'],'status'=>1,'pptype'=>$res['pptype'],'pa_order'=>$pa_order])->find();

            // dump($next);

            //die;

            $result=$product_package->where("id",$id)->setField("pa_order",$pa_order);

            $result1=$product_package->where("id",$next['id'])->setField("pa_order",$res['pa_order']);

            if($result && $result1){

                ajaxMsg();

            }else{

                ajaxMsg("数据下移失败",0);

            }

        }

    }



    /**

    资费项目

     * 20191120  田博

     **/

    public function product_chargeable(){

        $pid=input("get.pid");

        $fid=input("get.fid");

        $self_type=getArr('selfpay-type');

        $data=db("product_selfpay")->field("*")->where("pid",$pid)->select();

        ///dump($data);die;

        $list=$this->resort($data);

        //dump($list);

        foreach($list as $k=>$v){

            $res=db("product_selfpay")->field("*")->where("id",$v['fid'])->find();

            $list[$k]['fid_name']=$res['title'];

        }

        //dump($list);

        $this->assign([

            'list'=>$list,

            'fid'=>$fid,

            'pid'=>$pid,

            'self_type'=>$self_type,

        ]);

        return $this->view->fetch();

    }



    /**

    资费项目--添加

     * 20191120  田博

     **/

    public function chargeable_add(){

        $pid=input("get.pid");

        $fid=input("get.fid");

        $type=input('get.type');

        //dump($type);

        $self_type=getArr('selfpay-type');

        $product=db("product")->field("s_name,pricetype")->where("id",$pid)->find();

        if(Request()->isPost()){

            $res=db("product_selfpay")->field("id,pa_order")->where(['pid'=>$pid,'fid'=>$fid])->order("pa_order asc")->find();

            $res1=db("product_selfpay")->field("*")->where(['pid'=>$pid,'id'=>$fid])->find();

            $data=input("post.");

            //dump($res1);

            $selecttype=$res1['selecttype'];

            if($type<2 ){

                $data['selecttype']='';

            }elseif($type==2){

                $data['selecttype']=input("selecttype");

            }elseif($type==3){

                $data['selecttype']=$selecttype;

            }



            $data['pid']=$pid;

            $data['pptype']=$type;

            $data['fid']=$fid;

            $data['pa_order']=$res['pa_order']+1;

            $data['pricetype']=$product['pricetype'];

            // dump($data);die;

            $result=db("product_selfpay")->insert($data);

            if($result){

                $this->success("自费项目添加成功","/admin/product/product_chargeable?pid={$pid}&fid=0");

            }else{

                $this->error("自费项目添加失败");

            }

        }

        $this->assign([

            'name'=>$product['s_name'],

            'type'=>$type,

            'self_type'=>$self_type,

            'pid'=>$pid

        ]);

        return $this->view->fetch();

    }

    /**

    资费项目--修改

     * 20191121  田博

     **/

    public function chargeable_edit(){

        $id=input("get.id");

        $res=db("product_selfpay")->field("*")->where("id",$id)->find();

        $self_type=getArr('selfpay-type');

        $product=db("product")->field("s_name")->where("id",$res['pid'])->find();

        if(Request()->isPost()){

            $data=input("post.");

            $result=db("product_selfpay")->update($data);

            if($result){

                $this->success("资费项目修改成功","/admin/product/product_chargeable?pid={$res['pid']}&fid=0");

            }else{

                $this->error("资费项目修改失败");

            }

        }

        $this->assign([

            'res'=>$res,

            'self_type'=>$self_type,

            'name'=>$product['s_name'],



        ]);



        return $this->view->fetch();

    }



    ////////////查找自费项目的 所有子节点//////////////////////



    public function resort($data,$fid=0,$pptype=0){

        static $ret=array();

        foreach ($data as $k=>$v) {

            if($v['fid']==$fid){

                $v['level']=$pptype;

                $ret[]=$v;

                $this->resort($data,$v['id'],$pptype+1);

            }

        }

        return $ret;

    }



    /**

    资费项目--删除

     * 20191122  田博

     **/



    public function chargeable_del(){

        $product_selfpay=db("product_selfpay");

        $id=input("post.id");

        $res=$product_selfpay->field("*")->where("id",$id)->find();

        $data=$product_selfpay->field("*")->where(['pid'=>$res['pid']])->select();

        $list=$this->resort($data,$id,$res['pptype']);

        foreach($list as $k=>$v){

            if($v['pptype']==3){

                $spprice_list=db("product_spprice")->where("sp_id",$v['id'])->select();

                foreach($spprice_list as $k1=>$v1){

                    $spprice_list_res=db("product_spprice")->delete($v1['id']);

                    if(!$spprice_list_res){

                        ajaxMsg("该自费项目的价格删除失败",0);

                        return;

                    }

                }

            }

            $son_id=$product_selfpay->delete($v['id']);

            if(!$son_id){

                ajaxMsg("该自费项目的子节点删除失败",0);

                return;

            }

        }



        $result=$product_selfpay->delete($id);

        if($result){

            ajaxMsg("该自费项目删除成功",1);

        }else{

            ajaxMsg("该自费项目删除失败",0);

        }

    }



    /**

    资费项目--资费项目价格删除

     * 20191125  田博

     **/



    public function chargeable_del_price(){

        $product_spprice=db("product_spprice");

        $product_selfpay=db("product_selfpay");

        $id=input("post.id");



        $res=$product_spprice->where("sp_id",$id)->select();

        $res1=$product_selfpay->where("id",$id)->find();



        foreach($res as $k=>$v){

            $product_spprice->delete($v['id']);

        }

        $result=$product_selfpay->delete($res1['id']);



        if($result){

            ajaxMsg("该自费项目价格删除成功",1);

        }else{

            ajaxMsg("该自费项目价格删除失败",0);

        }



    }









    /**

    资费项目--自由行产品添加判断

     * 20191122  田博

     **/

    public function chargeable_zyx_add(){

        $id=input("post.id");

        $count=db("product_selfpay")->where(['fid'=>$id])->count();

        if($count==1){

            ajaxMsg("多选组只能选择一个",0);

        }else{

            ajaxMsg();

        }

    }

    /**

    资费项目--自由行产品列表

     * 20191122  田博

     **/

    public function chargeable_zyx_list(){

        $id=input("get.id");

        $where['p_type']=4;

        $where['status']=array("lt",4);

        $product=db("product")->field("id as pro_id,s_name")->where($where)->select();

        // dump($product);

        foreach($product as $k=>$v){

            $list=db("product_package")->field("*")->where(['p_id'=>$v['pro_id'],'pptype'=>2])->order("selecttype asc")->select();

            if(!empty($list)){

                $product[$k]['list']= $list;

            }else{

                $product[$k]['list']= '';

            }

        }

        $product_package=array();

        foreach($product as $k=>$v){

            if($v['list']!=''){

                $product_package[]=$v;

            }

        }

        $this->assign([

            'package_list'=>$product_package,

            'id'=>$id,

        ]);

        return $this->view->fetch();

    }

    /**

    资费项目--自由行产品列表添加

     * 20191125  田博

     **/

    public function chargeable_zyx_list_add(){

        if(Request()->isPost()){

            $fid=input("post.id");

            $pid=input("post.pid");

            $package_id=input("post.package_id");

            $packageRes=db("product_package")->find($package_id);

            //获取父级信息

            $res=db("product_selfpay")->where(['id'=>$fid])->find();

            $res1=db("product_selfpay")->where("fid",$fid)->order("pa_order asc")->find();

            $pa_order=$res1['pa_order']+1;

            $product=db("product")->field("s_name,pricetype")->where("id",$pid)->find();

            $data['pid']=$res['pid'];

            $data['fid']=$fid;

            $data['pptype']=3;

            $data['spp_id']=$pid;

            $data['sppackageid']=$package_id;



            $data['title']=$product['s_name']."-".$packageRes['ptitle'];

            $data['status']=1;

            $data['selecttype']=$res['selecttype'];

            $data['pa_order']=$pa_order;

            $data['pricetype']=$product['pricetype'];



            $result=db("product_selfpay")->insert($data);



            if($result){

                ajaxMsg();

            }else{

                ajaxMsg("自由行产品列表添加失败",0);

            }

        }

    }



    /**

    资费项目--价格维护

     * 20191125  田博

     **/

    public function chargeable_edit_price(){

        //dump(input("get."));//db("product_selfpay")

        $id=input("get.id");

        $product_spprice=db("product_spprice");

        $product_selfpay=db("product_selfpay");

        $onehouse=$product_selfpay->field("*")->where("id",$id)->find();

        if(input("pricetype")==1){

            $result_num1=$product_spprice->where(['sp_id'=>$id,'p_num'=>1])->find();

            $result_num2=$product_spprice->where(['sp_id'=>$id,'p_num'=>2])->find();

            $result_num3=$product_spprice->where(['sp_id'=>$id,'p_num'=>3])->find();

            $result_num4=$product_spprice->where(['sp_id'=>$id,'p_num'=>4])->find();



            $this->assign([

                'result_num1'=>$result_num1,

                'result_num2'=>$result_num2,

                'result_num3'=>$result_num3,

                'result_num4'=>$result_num4,



            ]);

        }else{

            $result_num=$product_spprice->where(['sp_id'=>$id,'p_num'=>1])->find();

            //dump($result_num);

            $this->assign([

                'result_num'=>$result_num,

            ]);

        }



        $res=db("product_selfpay")->where("id",$id)->find();

        $packagePrice=db("product_package")->find($res['sppackageid']);

        $product=db("product")->field("s_name")->where("id",$res['pid'])->find();

        if(Request()->isPost()){

            $list=$product_spprice->where("sp_id",$id)->select();

            if(count($list)){

                db("product_selfpay")->where("id",$id)->setField("onehouse",'');

                foreach($list as $k=>$v){

                    $list_res=$product_spprice->delete($v['id']);

                    if(!$list_res){

                        $this->error("价格维护失败");

                    }

                }

            }



            if(input("pricetype")==1){

                //dump(input("post."));die;

                if(input("price1")!=''){

                    $data1['p_id']=$res['pid'];

                    $data1['sp_id']=$res['id'];

                    $data1['spp_id']=$res['spp_id'];

                    $data1['sppackageid']=$res['sppackageid'];

                    $data1['p_num']=1;

                    $data1['price']=input("price1");

                    $data1['title']=input("title1");

                    $data1['info']=input("info1");

                    db("product_spprice")->insert($data1);

                }

                if(input("price2")!=''){

                    $data2['p_id']=$res['pid'];

                    $data2['sp_id']=$res['id'];

                    $data2['spp_id']=$res['spp_id'];

                    $data2['sppackageid']=$res['sppackageid'];

                    $data2['p_num']=2;

                    $data2['price']=input("price2");

                    $data2['title']=input("title2");

                    $data2['info']=input("info2");

                    db("product_spprice")->insert($data2);



                }

                if(input("price3")!=''){

                    $data3['p_id']=$res['pid'];

                    $data3['sp_id']=$res['id'];

                    $data3['spp_id']=$res['spp_id'];

                    $data3['sppackageid']=$res['sppackageid'];

                    $data3['p_num']=3;

                    $data3['price']=input("price3");

                    $data3['title']=input("title3");

                    $data3['info']=input("info3");

                    db("product_spprice")->insert($data3);

                }

                if(input("price4")!=''){

                    $num4=db("product_spprice")->where(['sp_id'=>$id,'p_num'=>4])->count();

                    $data4['p_id']=$res['pid'];

                    $data4['sp_id']=$res['id'];

                    $data4['spp_id']=$res['spp_id'];

                    $data4['sppackageid']=$res['sppackageid'];

                    $data4['p_num']=4;

                    $data4['price']=input("price4");

                    $data4['title']=input("title4");

                    $data4['info']=input("info4");

                    db("product_spprice")->insert($data4);

                }



            }else{



                if(input("price")!=''){

                    $num=db("product_spprice")->where(['sp_id'=>$id,'p_num'=>1])->count();

                    $data['p_id']=$res['pid'];

                    $data['sp_id']=$res['id'];

                    $data['spp_id']=$res['spp_id'];

                    $data['sppackageid']=$res['sppackageid'];

                    $data['p_num']=1;

                    $data['price']=input("price");

                    $data['title']=input("title");

                    $data['info']=input("info");

                    db("product_spprice")->insert($data);

                }

            }



            if(input("onehouse")){

                $onhouse1=input("onehouse");

                $update['onehouse']=$onhouse1;

                $result=db("product_selfpay")->where("id",$id)->update($update);

            }else{

                $result=true;

            }

            if($result){

                $this->success("价格维护成功","/admin/product/product_chargeable?pid={$res['pid']}&fid=0");

            }else{

                $this->error("价格维护失败");

            }

        }





        $this->assign([

            'res'=>$res,

            'name'=>$product['s_name'],

            'onehouse'=>$onehouse,

            'price'=>$packagePrice

        ]);

        return $this->view->fetch();

    }









    /**

    线路维护 向下移动

     * 20191025  田博

     **/

    public function product_line_down(){

        if(Request()->isAjax()){

            //dump(input("post."));die;

            $product_link=db("product_link");

            $id=input("id");//当前ID

            $next_id=input("next_id");//上一个ID

            $id_line=$product_link->field("l_order")->find($id);

            $next_line=$product_link->field("l_order")->find($next_id);

            $res=$product_link->where("id",$id)->setField("l_order",$next_line['l_order']);

            $res1=$product_link->where("id",$next_id)->setField("l_order",$id_line['l_order']);

            if($res && $res1){

                ajaxMsg("线路向下移动成功",1);

            }else{

                ajaxMsg("线路向下移动失败",0);

            }

        }



    }



    /**

    线路维护---加入线路

     * 20190927  田博

     **/





    public function product_line_add(){

        if(Request()->isAjax()){

            $product_link=db("product_link");

            //dump(input("post."));die;

            $pid=input("pid");

            $result=$product_link->field("linkno,l_order")->where("p_id",$pid)->find();

            // 当前 p_id 下的 a b线（除当前p_id） 更改 l_order 顺序排序

            $where['linkno']=$result['linkno'];

            $where['l_order']=array("gt",$result['l_order']);

            $list=$product_link->where($where)->select();

            foreach($list as $k=>$v){

                $arr=$v['l_order']-1;

                $product_link->where("id",$v['id'])->setField("l_order",$arr);

            }

            // 当前 p_id 下的 a b线 更改 l_order 顺序排序

            $linkNo=input("linkno");

            $data['linkno']=$linkNo;

            $count=$product_link->where("linkno",$linkNo)->count();

            $chr_A=1;

            $per=$chr_A+$count;

            $data['l_order']=$per;

            $res=$product_link->where("p_id",$pid)->update($data);

            if($res){

                echo 1;

            }else{

                echo 0;

            }

        }

    }







    /**

    线路维护---拆分线路

     * 20190927  田博

     **/

    public function product_line_split(){

        if(Request()->isAjax()){

            $product_link=db("product_link");

            $pid=input("pid");

            $result=$product_link->field("linkno,l_order")->where("p_id",$pid)->find();

            // 当前 p_id 下的 a b线（除当前p_id） 更改 l_order 顺序排序

            $where['linkno']=$result['linkno'];

            $where['l_order']=array("gt",$result['l_order']);

            $list=$product_link->where($where)->select();

            foreach($list as $k=>$v){

                $arr=$v['l_order']-1;

                $product_link->where("id",$v['id'])->setField("l_order",$arr);

            }

            // 当前 p_id 下的 a b线 更改 l_order 顺序排序

            $numId=db("num")->find();

            $poId=$numId['pno']+1;

            $linkno=$numId['linkno']+1;

            $data['linkno']=$linkno;

            $data['l_order']=1;

            $res=$product_link->where("p_id",$pid)->update($data);

            $data2['pno']=$poId;

            $data2['linkno']=$linkno;

            db("num")->where("id",1)->update($data2);

            if($res){

                echo 1;

            }else{

                echo 0;

            }

        }

    }



//套餐对应的行程   20191127 田博

    public function route_common_del($id,$pid){



        //套餐对应的行程

        $paroduct_route=db("route");

        $product_route_info=db("route_info");

        $route_img=db("route_info_img");

        $route=$paroduct_route->field("id")->where(['p_id'=>$pid,'package_id'=>$id])->select();

        // dump($route);//die;

        if(is_array($route)){

            foreach($route as $k=>$v){

                $route_info=$product_route_info->field("tr_id,id")->where("tr_id",$v['id'])->select();

                //dump($route_info);

                foreach($route_info as $kk=>$vv){

                    $img_list=$route_img->field("*")->where("tri_id",$vv['id'])->select();

                    // dump($img_list);

                    foreach ($img_list as $k1=>$v1){

                        $thumb=explode("/",$v1['imgadr']);

                        //dump($thumb);die;

                        $thumb_img=ROOT_PATH . 'public'."/".$thumb['1']."/".$thumb['2']."/"."200_120"."/".$thumb['3'];

                        $imgpath=ROOT_PATH . 'public'.$v1['imgadr'];



                        //删除图片文件(夹)

                        if($vv['itype']!=7){

                            @unlink($imgpath);

                            @unlink($thumb_img);

                        }

                        //删除图片库中info子数据

                        $img_res=$route_img->delete($v1['id']);

                        if(!$img_res){

                            ajaxMsg("行程内容图片删除成功",0);

                            return;

                        }

                    }

                    $info_res=$product_route_info->delete($vv['id']);

                    if(!$info_res){

                        ajaxMsg("行程内容删除失败",0);

                        return;

                    }

                }

                $route_res=$paroduct_route->delete($v['id']);

                if(!$route_res){

                    ajaxMsg("行程删除失败",0);

                    return;

                }

            }

        }



    }





    /**

     *行程详情图片排序

     *20190909  田博

     */



    public function route_sort_img(){

        $route_info_img=db("route_info_img");

        $data=input("post.");

        //dump($data);die;

        $tr_id=$data['tr_id'];

        foreach ($data['imgsort'] as $k=>$v){

            $route_info_img->where("id",$k)->setField("imgsort",$v);

        }

        foreach ($data['imgtitle'] as $k1=>$v1){

            $route_info_img->where("id",$k1)->setField("imgtitle",$v1);

        }

        $this->redirect('product/route_index?p_id='.$data['p_id'].'&package_id='.$data['package_id'].'#dinfo'.$tr_id);



    }





    /**

     *天数列表

     *

     */

    function route_index()

    {

        //所有行程列表页面都需要获取产品id

        $url=request()->url(true);

        //dump($url);

        $p_id=input('p_id');

        $package_id=input("package_id");

        $slist=[];

        $list=db('route')->where(['p_id'=>$p_id,'package_id'=>$package_id])->order('day_no asc')->select();

        // dump($list);

        foreach($list as $lists){



            $list1=db('route_info')->where("tr_id=".$lists['id'])->order('itype asc,id asc')->select();

            $slist1=[];

            foreach($list1 as $lists1){

                $list2=db('route_info_img')->where("tri_id=".$lists1['id'])->select();

                $slist2=[];

                foreach($list2 as $lists2){

                    $slist2[]=$lists2;

                }

                $lists1["infoimg"]=$slist2;

                $slist1[]=$lists1;

            }

            $lists["darr"]=$slist1;

            $slist[]=$lists;

        }

        //dump($slist);



        $count=count($slist);

        //dump($count);

        $this->view->assign("list", $slist);

        $this->view->assign("p_id", $p_id);

        $this->view->assign("count", $count);

        $this->view->assign("package_id", $package_id);

        return $this->view->fetch();

    }



    /**

     *天数增加

     *

     */



    public function route_add()

    {

        if(Request()->isAjax()){

            ///dump(input("post."));die;

            $p_id=input("p_id");

            $titlearr=input("titlearr");

            $day_no=input("day_no");

            $package_id=input("package_id");

            $this->model = model('app\admin\model\Product');

            $data= [

                'p_id' => $p_id,

                'titlearr' => $titlearr,

                'day_no' => $day_no,

                'package_id' => $package_id,

            ];

            $inid=$this->model->route_add_M($data);

            set_route_day($p_id,$package_id);

            // $this->redirect('product/route_index?p_id='.$p_id.'#dno'.$inid);

            $inid=intval($inid);

            //dump($inid);//die;

            if($inid){

                echo $inid;

            }else{

                echo 0;

            }

        }else{

            return $this->view->fetch();

        }







    }





    /**

     *行程内容向后一天移

     * 20191127 田博

     */

    public function product_route_move(){

        if(Request()->isAjax()){

            $id=input("post.id");

            $pid=input("post.pid");

            $package_id=input("post.package_id");

            $day_no=input("post.day_no");

            $flag=input("post.flag");

            if($flag==1){

                $days=$day_no-1;

            }else{

                $days=$day_no+1;

            }

            $res=db("route")->where(['p_id'=>$pid,'package_id'=>$package_id,'day_no'=>$days])->find();

            //dump($res);die;



            $prev=db("route")->where(['p_id'=>$pid,'package_id'=>$package_id,'id'=>$res['id']])->setField("day_no",$day_no);

            $next=db("route")->where(['p_id'=>$pid,'package_id'=>$package_id,'id'=>$id])->setField("day_no",$days);



            if($prev && $next){

                ajaxMsg();

            }else{

                ajaxMsg("行程移动失败",0);

            }



        }

    }



    /**

     *行程套餐

     *田博 20191125

     */



    public function route_package(){

        $pid=input("get.pid");

        $list=db("product_package")->where(["p_id"=>$pid,'pptype'=>2])->select();

        foreach($list as $k=>$v){

            $res=db("product_package")->field("ptitle")->where("id",$v['fid'])->find();

            //$count=db('route')->where(["p_id"=>$pid,"package_id"=>$v['id']])->count();

            $list[$k]['father_title']=$res['ptitle'];

            // $list[$k]['count']=$count;



        }

        //dump($list);die;

        $pptype=getArr('package-type');

        $this->assign([

            'list'=>$list,

            'pptype'=>$pptype,

        ]);

        return $this->view->fetch();

    }





    /**

     *行程复制添加

     *田博 20191125

     */

    public function route_copy_add(){

        if(Request()->isAjax()){

            //"copy_id":copy_id,"pid":pid,"package_id":package_id

            //dump(input("post."));//die;

            $copy_id=input("post.copy_id");//需要复制套餐id

            $package_id=input("post.package_id");//当前套餐的ID

            $pid=input("post.pid");//产品ID

            $this->route_common_del($package_id,$pid);

            //die;

            //route  route_info  route_info_img

            $list=db("route")->where(['package_id'=>$copy_id,'p_id'=>$pid])->select();

            foreach($list as $k=>$v){

                $data['p_id']=$v['p_id'];

                $data['package_id']=$package_id;

                $data['day_no']=$v['day_no'];

                $data['type_sort']=$v['type_sort'];

                $data['titlearr']=$v['titlearr'];

                $result=db("route")->insertGetId($data);

                if(!$result){

                    ajaxMsg("行程表复制失败",0);

                    return;

                }



                $list_info=db("route_info")->where("tr_id",$v['id'])->select();

                foreach($list_info as $k1=>$v1){

                    $data1['tr_id']=$result;

                    $data1['title']=$v1['title'];

                    $data1['info']=$v1['info'];

                    $data1['linkid']=$v1['linkid'];

                    $data1['sort']=$v1['sort'];

                    $data1['tagid']=$v1['tagid'];

                    $data1['itype']=$v1['itype'];

                    $data1['imgarr']=$v1['imgarr'];

                    $data1['fid']=$v1['fid'];

                    $data1['infotime']=$v1['infotime'];

                    $result1=db("route_info")->insertGetId($data1);

                    if(!$result1){

                        ajaxMsg("行程详情表复制失败",0);

                        return;

                    }



                    $list_info_img=db("route_info_img")->where("tri_id",$v1['id'])->select();



                    foreach($list_info_img as $k2=>$v2){

                        /*$thumb_url=explode("/",$v2['imgadr']);

                        $date=date("Ymd",time());

                        $date_path=ROOT_PATH . 'public'."/uploads/".$date;

                        if(!file_exists($date_path)){

                            mkdir($date_path,0777,true);

                        }

                        $url=ROOT_PATH . 'public'.$v2['imgadr'];

                        if(file_exists($url)){

                            $toURL=$date_path."/".$v2['id'].$thumb_url[3];

                            copy($url,$toURL);

                            $uploadURL="/uploads/".$date."/".$v2['id'].$thumb_url[3];

                        }else{

                            $uploadURL=$v2['imgadr'];

                        }*/

                        $data2['tri_id']=$result1;

                        $data2['imgadr']=$v2['imgadr'];

                        $data2['imgtitle']=$v2['imgtitle'];

                        $data2['imginfo']=$v2['imginfo'];

                        $data2['imglink']=$v2['imglink'];

                        $data2['imgsort']=$v2['imgsort'];



                        $result2=db("route_info_img")->insertGetId($data2);



                        if(!$result2){

                            ajaxMsg("行程详情图片表复制失败",0);

                            return;

                        }



                    }

                }

            }

            set_route_day($pid,$package_id);

            ajaxMsg("所有行程复制成功",1);

        }



    }









    /**

    产品套餐删除

     * 20191211  田博

     **/



    public function package_del(){



        if(request()->isAjax()){

            $data=input("post.");

            $res=db("product_package")->where(["id"=>$data['id'],"p_id"=>$data['pid']])->find();

            $list=db("product_package")->where(["p_id"=>$data['pid']])->select();

            //dump($res);

            $lists=$this->package_resort($list,$data['id'],$res['pptype']);

            //dump($lists);
            



            //die;



            //// $packageArr=[];

            foreach($lists as $k=>$v){

                if($v['pptype']==2){

                    $wherep['p_id']=$v['p_id'];

                    $wherep['pa_showchar']=array("gt",$v['pa_showchar']);

                    $packArr=db("product_package")->where($wherep)->select();

                    foreach($packArr as $k3=>$v3){

                        $str=ord($v3['pa_showchar'])-1;

                        $char=chr($str);

                        db("product_package")->where("id",$v3['id'])->update(['pa_showchar'=>$char]);

                    }

                    //删除团期

                    $groupList=db("product_group")->where(['p_id'=>$v['p_id'],"package_id"=>$v['id']])->select();

                    foreach($groupList as $k1=>$v1){



                        $groupPrice=db("product_price_a")->where(['p_id'=>$v1['p_id'],"group_id"=>$v1['id'],"package_id"=>$v1['package_id']])->select();

                        foreach($groupPrice as $k2=>$v2){

                            $price_result=db("product_price_a")->delete($v2['id']);

                            if(!$price_result){

                                ajaxMsg("套餐团期价格删除失败",0);

                            }

                        }

                        $result=db("product_group")->delete($v1['id']);

                        if(!$result){

                            ajaxMsg("套餐团期删除失败",0);

                        }

                    }

                    //route_common_del($id,$pid)

                    $this->route_common_del($v['id'],$v['p_id']);

                }

                $package_res=db("product_package")->delete($v['id']);

                if(!$package_res){

                    ajaxMsg("该套餐子节点删除失败",0);

                }

            }

            db("product_group")->where(["p_id"=>$data['pid'],"package_id"=>$data['id']])->delete();
            db("product_price_a")->where(["p_id"=>$data['pid'],"package_id"=>$data['id']])->delete();
            $package_result=db("product_package")->delete($data['id']);



            $package_count=db("product_package")->where(["p_id"=>$data['pid'],"pptype"=>2])->count();

            if($package_count<2){

                db("product")->where("id",$data['pid'])->update(['havepackage'=>0]);

            }





            if($package_result){

                ajaxMsg("该套餐删除完成",1);

            }else{

                ajaxMsg("该套餐删除失败",0);

            }



        }

    }

    /**

    查找套餐所有的子节点

     * 20191211  田博

     **/

    public function package_resort($data,$fid=0,$pptype=0){

        static $ret=array();

        foreach ($data as $k=>$v) {

            if($v['fid']==$fid){

                $v['level']=$pptype;

                $ret[]=$v;

                $this->package_resort($data,$v['id'],$pptype+1);

            }

        }

        return $ret;

    }





//////////////////////////////////////////////////////////////



    /**

     *团期复制添加

     *田博 20191125

     */



    public function group_copy_add(){

        if(Request()->isAjax()){

            //"copy_id":copy_id,"pid":pid,"package_id":package_id

            //dump(input("post."));//die;

            $copy_id=input("post.copy_id");//需要复制套餐id

            $package_id=input("post.package_id");//当前套餐的ID

            $pid=input("post.pid");//产品ID

            $this->group_common_del($package_id,$pid);



            //copy_group

            $groupList=db("product_group")->where(['p_id'=>$pid,"package_id"=>$copy_id])->select();

            foreach($groupList as $k=>$v){

                //$price_count=db("product_price_a")->where("group_id",$v['id'])->count();



                $data['p_id']=$v['p_id'];

                $data['package_id']=$package_id;

                $data['g_time']=$v['g_time'];

                $data['status']=$v['status'];

                $data['g_max']=$v['g_max'];

                $data['discount']=$v['discount'];

                $data['childrenprice']=$v['childrenprice'];

                $data['onehouse']=$v['onehouse'];

                $data['discounttype']=$v['industry_share'];

                $data['housetype']=$v['housetype'];

                $data['info']=$v['info'];

                $data['pricetype']=$v['pricetype'];

                $data['grouptype']=$v['grouptype'];

                $data['season_type']=$v['season_type'];

                $data['season_info']=$v['season_info'];

                $data['selfpay_id']=$v['selfpay_id'];

                $result=db("product_group")->insertGetId($data);



                if(!$result){

                    ajaxMsg("团期表复制失败",0);

                    return;

                }



                $priceList=db("product_price_a")->where("group_id",$v['id'])->select();



                foreach($priceList as $k1=>$v1){



                    $data1['p_id']=$v1['p_id'];

                    $data1['group_id']=$result;

                    $data1['package_id']=$package_id;

                    $data1['p_num']=$v1['p_num'];

                    $data1['price']=$v1['price'];

                    $data1['title']=$v1['title'];

                    $data1['info']=$v1['info'];

                    $data1['info']=$v1['info'];



                    $result1=db("product_price_a")->insertGetId($data1);



                    if(!$result1){

                        ajaxMsg("团期价格表复制失败",0);

                        return;

                    }

                }

            }

            set_low_price($pid);

            ajaxMsg("所有团期复制成功",1);

        }



    }



    //删除团期

    public function group_common_del($package_id,$pid){



        $groupList=db("product_group")->where(['p_id'=>$pid,"package_id"=>$package_id])->select();

        foreach($groupList as $k1=>$v1){



            $groupPrice=db("product_price_a")->where(['p_id'=>$v1['p_id'],"group_id"=>$v1['id'],"package_id"=>$v1['package_id']])->select();

            foreach($groupPrice as $k2=>$v2){

                $price_result=db("product_price_a")->delete($v2['id']);

                if(!$price_result){

                    ajaxMsg("套餐团期价格删除失败",0);

                }

            }

            $result=db("product_group")->delete($v1['id']);

            if(!$result){

                ajaxMsg("套餐团期删除失败",0);

            }

        }

    }

    /**

     *行程复制

     *田博 20191125

     */



    public function route_copy(){

        $id=input("get.id");

        $pid=input("get.pid");

        $flag=input("get.flag");

        $list=db("product_package")->where(["p_id"=>$pid,'pptype'=>2])->select();

        $arr=array();

        foreach($list as $k=>$v){

            if($v['id']!=$id){

                $arr[]= $v;

            }

        }

        // dump($arr);

        $this->assign([

            'id'=>$id,

            'pid'=>$pid,

            'flag'=>$flag,

            'arr'=>$arr,

        ]) ;

        return $this->view->fetch();

    }



    ////////////////////0209///////////////////////////////////////////

    ///

    public function product_package(){



        $pid=input("get.pid");

        $fid=input("get.fid");

        $pptype=getArr('package-type');

        $package=db("product_package");

        $data=$package->field("*")->where("p_id",$pid)->select();

        $list=$this->resort($data);

        foreach($list as $k=>$v){

            $res=$package->field("*")->where("id",$v['fid'])->find();

            $list[$k]['name']=$res['ptitle'];

        }

        $this->assign([

            'list'=>$list,

            'fid'=>$fid,

            'pid'=>$pid,

            'pptype'=>$pptype,

        ]);

        //die;

        return $this->view->fetch();

    }





    public function package_add(){

        $pid=input("get.pid");

        $fid=input('get.fid');

        $type=input('get.type');

        $package=db("product_package");

        //父级信息

        $res2=$package->field("id,pa_order,pptype,selecttype")->where(['p_id'=>$pid,'id'=>$fid])->order("pa_order asc")->find();

        //dump($res);



        $pptype=getArr('package-type');

        $product=db("product");

        $res=$product->field("s_name,pricetype,havepackage")->find($pid);



        if(Request()->isPost()){

            $res1=$package->field("id,pa_order,pptype")->where(['p_id'=>$pid,'fid'=>$fid,'pptype'=>$type])->order("pa_order desc")->find();

            $data=input("post.");

            $pa_order=$res1['pa_order']+1;

            if($type==2){

                $selecttype=$res2['selecttype'];

                $data['selecttype']=$selecttype;

                $pa_showchar=db("product_package")->where(["p_id"=>$pid,'pptype'=>2])->order("pa_showchar desc")->find();

                $str=ord($pa_showchar['pa_showchar']);

                $str=$str+1;//chr

                $data['pa_showchar']=chr($str);

            }

            $data['pptype']=$type;

            $data['pa_order']=$pa_order;

            $data['pricetype']=$res['pricetype'];

            $data['pptype']=$type;

            $data['fid']=$fid;

            $data['p_id']=$pid;

            $result=$package->insert($data);



            $package_count= db("product_package")->where(["p_id"=>$pid,'pptype'=>2])->count();

            if($res['havepackage']==0){

                if($package_count){

                    $product->where("id",$pid)->update(['havepackage'=>1]);

                }

            }



            if($result){

                $this->success("产品套餐添加成功","/admin/product/product_package?pid=$pid&fid=0");

            }else{

                $this->error("产品套餐添加失败");

            }

        }







        $this->assign([

            'res'=>$res,

            'pid'=>$pid,

            'fid'=>$fid,

            'type'=>$type,

            'pptype'=>$pptype,

        ]);

        return $this->view->fetch();

    }









    public function package_edit(){

        $id=input("get.id");

        $package=db("product_package");

        $product=db("product");

        $res=$package->field("*")->find($id);

        //dump($res);

        $pptype=getArr('package-type');

        $name=$product->field("s_name")->find($res['p_id']);



        if(request()->isPost()){

            $data=input("post.");

            $result=$package->update($data);

            if($result){

                $this->success("产品套餐修改成功","/admin/product/product_package?pid={$res['p_id']}&fid=0");

            }else{

                $this->error("产品套餐修改失败");

            }

        }

        $this->assign([

            'res'=>$res,

            'name'=>$name,

            'pptype'=>$pptype,

        ]);

        return $this->view->fetch();

    }







    //产品上线数据处理

    public function product_status(){

        if(Request()->isAjax()){

            $data=input("post.");

            $id=input("post.id");

            $status=input("post.status");



            $flag=$this->set_product_data($id);



            if($flag!==false){

                ajaxMsg("产品上线更新成功",1);

            }else{

                ajaxMsg("数据修改失败",0);

            }

        }

    }









    public function set_product_data($id){

        $package=db("product_package");

        $group=db("product_group");

        $route=db("route");

        $product=db("product");

        //设置产品主表主图

        $pro_img_res=db("product_adimg")->where(["p_id"=>$id,"ismain"=>1])->find();

        if($pro_img_res){

            $product->where("id",$id)->update(["proimg"=>$pro_img_res['imgurl']]);

        }





        // 检查套餐个数----更新产品主表 havepackage字段

        $package_count=$package->where(["p_id"=>$id,"pptype"=>2,"status"=>array("neq",2)])->count();

        if($package_count==0){

            ajaxMsg("该产品还未添加套餐",0);

        }

        if($package_count==1){

            $data['havepackage']=0;

        }else{

            $data['havepackage']=1;

        }

        $product->where("id",$id)->update($data);

        //  若某个套餐没有设置起止城市，需要提示 ，并校验不通过

        $wherePackage['p_id']=$id;

        $wherePackage['pptype']=2;

        $wherePackage['status']=array("neq",2);

        $packageList=$package->where($wherePackage)->select();



        //dump($packageList);//die;

        foreach($packageList as $k=>$v){

            if($v['startcityid']=='' || $v['startcity']=='' || $v['endcityid']=='' || $v['endcity']==''){

                $message=$v['ptitle']."套餐起止城市信息不全";

                ajaxMsg($message,0);

            }



            //   检查每个套餐必须有团期，若没有需要校验并提示
            $p_type = $product->where("id",$id)->find();
            if($p_type['p_type'] == 2){
                $p_type = db("product_tour")->where(["p_id"=>$id,"package_id"=>$v['id']])->count();
                if($p_type==0){
                    $message=$v['ptitle']."暂无团期,请补全团期";
                    ajaxMsg($message,0);
                }
            }else{
                $group_count=$group->where(["p_id"=>$id,"package_id"=>$v['id'],"g_time"=>array("gt",time())])->count();
                if($group_count==0){
                    $message=$v['ptitle']."套餐暂无团期,请补全团期";
                    ajaxMsg($message,0);
                }
        }





            //  根据行程 计算天数    ---更新 套餐表行程   产品表行程

            $route_count=$route->where(["p_id"=>$id,"package_id"=>$v['id']])->count();

            if($route_count==0){

                $message=$v['ptitle']."套餐暂无行程,请补全行程";

                ajaxMsg($message,0);

            }

            $packageData['p_day']=$route_count;

            $package->where(["p_id"=>$id,"id"=>$v['id']])->update($packageData);



            //  检查每个套餐 起止城市---更新产品主表起止城市  为  A套餐起止城市（包括id）

            if($v['pa_showchar']=="A"){

                $data1['startcityid']=$v['startcityid'];

                $data1['startcity']=$v['startcity'];

                $data1['endcityid']=$v['endcityid'];

                $data1['endcity']=$v['endcity'];

                $data1['p_day']=$v['p_day'];

                $product->where("id",$id)->update($data1);

            }

        }

        //  设置每个团期最低价最高折扣  套餐最低价最高折扣   产品最低价最高折扣

        set_low_price($id);

        // 根据套餐起止城市  生成   产品城市标签（需要先判断产品有没有这个标签）

        //删除场景

       

        //$this->global_senec_list=db("product_mark")->where(["p_id"=>$id,"mark_type"=>array("in","1,2,5,6,7,8,9")])->select();

        //db("product_mark")->where(["p_id"=>$id,"mark_type"=>array("in","1,2,5,6,7,8,9")])->delete();

        /*foreach($senec_list as $k=>$v){

            db("product_mark")->delete($v['id']);

        }*/



        $map['p_id'] = $id;

        $map['mark_type'] = array('in',"1,2,5,6,7,8,9");

        $this->global_senec_list=db("product_mark")->where($map)->select();

      

        if($this->global_senec_list){

            foreach($this->global_senec_list as $key1 => $val1){

               $dateee = db("product_mark")->where('id='.$val1['id'])->delete();

            }

          }

  

        foreach($packageList as $k1=>$v1){



            //开始城市

            $this->findMarkLibraryCount($v1['startcity'],$id,2);

            //开始城市对应国家

            $father_res=$this->findCountry($v1['startcity']);

            $this->findMarkLibrarycount($father_res['p_name'],$id,8);

            //开始城市对应国家 对应区域  place_mark

            $this->findArea($father_res['p_name'],$id,1);

           

            //结束城市

            $this->findMarkLibraryCount($v1['endcity'],$id,6);

            //结束城市对应国家

            $father_res_end=$this->findCountry($v1['endcity']);

            $this->findMarkLibrarycount($father_res_end['p_name'],$id,8);

            //结束城市对应国家 对应区域  place_mark

            $this->findArea($father_res_end['p_name'],$id,1);

            // 根据 套餐 行程  生成天数标签  （如 6日游  7日游）

            $dayName=$v1['p_day']."日游";

            $this->findMarkLibrarycount($dayName,$id,5);



            // 根据 套餐行程内的景点  生成  产品经典标签（需要先判断产品有没有这个标签）

            $routeList=$route->where(['p_id'=>$id,"package_id"=>$v1['id']])->select();

          

            foreach($routeList as $k2=>$v2){

                $scenList=db("route_info")->where(["tr_id"=>$v2['id'],"itype"=>7])->select();

               

                foreach($scenList as $k3=>$v3){

                    //景点

                    if($v3['linkid']!=""){

                        $this->findMarkSenceCount($id,7,$v3['linkid']);

                        $father_temp=db("place")->find($v3['linkid']);

                        //景点对应城市

                        $father_res_city=$this->findCountry($father_temp['p_name']);

                    }else{

                        $this->findMarkLibraryCount($v3['title'],$id,7);

                        //景点对应城市

                        $father_res_city=$this->findCountry($v3['title']);

                    }

                   

                    //$father_res_city=$this->findCountry($v3['title']);

                    $this->findMarkLibrarycount($father_res_city['p_name'],$id,9);

                    //景点对应城市对应国家

                    $father_res_country=$this->findCountry($father_res_city['p_name']);

                    $this->findMarkLibrarycount($father_res_country['p_name'],$id,8);

                    

                    $this->findArea($father_res_end['p_name'],$id,1);

                   

                }

               

            }

           

        }

       

        //重点** 更新  产品主表  seotext  （）^



        $product_res=$product->find($id);

        // 产品ID^产品名程^短名称^英文名称^ .....后面的是产品标签库中的内容

        //16^意大利罗马斗兽场+西班牙广场+特莱维喷泉+万神殿一日游(免排队门票+参观精华景点)^罗马古城一日游^One-day tour of ancient Rome^波兰^欧洲^巴黎^法国^VanAbbe博物馆^埃因霍温^荷兰^1日游

        $text=$product_res['id']."^".$product_res['p_name']."^".$product_res['s_name']."^".$product_res['e_name'];

       

        $markList=db("product_mark")->where("p_id",$id)->select();

        $text1="";

        for($i=0;$i<count($markList);$i++){

            $text1=$text1."^" .$markList[$i]['mark_info'];

        }

        $text1=substr($text1,1);

        $text=$text."^".$text1;

        $res=$product->where("id",$id)->update(['seotext'=>$text,"status"=>3]);

       

        return $res;

    }

    //获取当前产品是否有该标签

    public function findMarkCount($pid,$name,$type){

        $mark=db("product_mark");

        $whereMark['p_id']=$pid;

        $whereMark['mark_info']=$name;

        $whereMark['mark_type']=$type;

        $mark_count=$mark->where($whereMark)->count();

        return $mark_count;

    }







    //景点

    public function findMarkSenceCount($id,$type,$place_id){

        $place = db("place");

        $res = $place->where("id", $place_id)->find();

        $markInfoRes=db("mark")->where("mark_info",$res['p_name'])->find();

        if(empty($markInfoRes)){

            //添加到标签库

            $row=$this->set_mark($res['p_name'],$type,$res['id'],$res['fid']);

            $mark_count=$this->findMarkCount($id,$res['p_name'],$type);

            if($mark_count==0){

                $this->set_product_mark($id,$row,$res['p_name'],7,0,$type,$res['id'],$res['fid']);

            }

        }else{

            if($markInfoRes['place_id']==''){

                db("mark")->where("id",$markInfoRes['id'])->update(['place_id'=>$res['id'],'place_fid'=>$res['fid']]);

            }

            $mark_count=$this->findMarkCount($id,$res['p_name'],$type);

            if($mark_count==0){

                $this->set_product_mark($id,$markInfoRes['id'],$res['p_name'],7,0,$type,$markInfoRes['place_id'],$markInfoRes['place_fid']);

            }



        }



    }



    //判断标签库中   判断产品标签库

    //$name 城市 景点 国家名   产品id  $type 标签类型

    public function findMarkLibraryCount($name,$id,$type){

        $markInfoRes=db("mark")->where("mark_info",$name)->find();

        //判断标签库中是否存在 存在则判断产品标签库  不存在则添加

        if(empty($markInfoRes)){

            //添加到标签库

            $place = db("place");

            $res = $place->where("p_name", $name)->find();

            $row=$this->set_mark($name,$type,$res['id'],$res['fid']);

            $mark_count=$this->findMarkCount($id,$name,$type);

            if($mark_count==0){

                $this->set_product_mark($id,$row,$name,7,0,$type,$res['id'],$res['fid']);

            }

        }else{

            if($markInfoRes['place_id']==''){

                $place = db("place");

                $res1 = $place->where("p_name", $name)->find();

                db("mark")->where("id",$markInfoRes['id'])->update(['place_id'=>$res1['id'],'place_fid'=>$res1['fid']]);

            }

            $mark_count=$this->findMarkCount($id,$name,$type);

            if($mark_count==0){

                $this->set_product_mark($id,$markInfoRes['id'],$name,7,0,$type,$markInfoRes['place_id'],$markInfoRes['place_fid']);

            }



        }



    }



    //根据国家查询相关区域



    public function findArea($name,$id,$type){

        $place = db("place");

        $res = $place->where("p_name", $name)->find();



        $list=db("place_mark")->where("place_id",$res['id'])->select();



        if(!empty($list)){

            foreach($list as $k=>$v){

                $this->findMarkLibraryCount1($v['mark_info'],$id,$type);

            }



        }

    }



    public function findMarkLibraryCount1($name,$id,$type){

        $markInfoRes=db("mark")->where("mark_info",$name)->find();

        //判断标签库中是否存在 存在则判断产品标签库  不存在则添加

        if(empty($markInfoRes)){

            //添加到标签库

            // $place = db("place");

            /// $res = $place->where("p_name", $name)->find();

            $row=$this->set_mark($name,$type,"","");

            $mark_count=$this->findMarkCount($id,$name,$type);

            if($mark_count==0){

                $this->set_product_mark($id,$row,$name,7,0,$type,"","");

            }

        }else{



            $mark_count=$this->findMarkCount($id,$name,$type);

            if($mark_count==0){

                $this->set_product_mark($id,$markInfoRes['id'],$name,7,0,$type,$markInfoRes['place_id'],$markInfoRes['place_fid']);

            }



        }



    }





    //根据当前的城市名称寻找相应的国家

    public function findCountry($city_name)

    {

        $place = db("place");

        $res = $place->where("p_name", $city_name)->find();

        $father_res = $place->where("id", $res['fid'])->find();

        return $father_res;

    }

    //添加产品标签

    public function set_product_mark($pid,$mark_id,$mark_info,$senec,$isself,$mark_type,$place_id,$place_fid){

        $count=db("product_mark")->where("p_id",$pid)->count();

        $fid=db("mark")->find($mark_id);

        //

        //dump($this->global_senec_list);//die;

        //利用已经存储的被删除标签查找状态相等的标签，修改状态

        $stylename='1';

      $slist=$this->global_senec_list;

         foreach ($slist as $k=>$v){

             if($v['mark_id']==$mark_id && $v['mark_type']==$mark_type && $v['senec']=='5'){

                 $senec='5';

                 $stylename=$v['stylename'];

             }

         }

        $mark['stylename']=$stylename;

        $mark['senec']=$senec;

        $mark['p_id']=$pid;

        $mark['mark_id']=$mark_id;

        $mark['mark_fid']=$fid['fid'];

        $mark['mark_info']=$mark_info;

        $mark['senec']=$senec;

        $mark['isself']=$isself;

        $mark['m_order']=$count+1;

        $mark['mark_type']=$mark_type;

        $mark['place_id']=$place_id;

        $mark['place_fid']=$place_fid;

        db("product_mark")->insert($mark);

    }



    //添加标签库



    public function set_mark($mark_info,$mark_type,$place_id,$place_fid){



        $mark['mark_info']=$mark_info;

        $mark['mark_type']=$mark_type;

        $mark['fid']=0;

        $mark['status']=0;

        $mark['ishot']=0;

        $mark['m_level']=1;

        $mark['place_id']=$place_id;

        $mark['place_fid']=$place_fid;

        $res=db("mark")->insertGetId($mark);

        return $res;

    }





    /*

    * 20200407

    * 田博

    * 行程维护

    * */



    public function route_day(){

        $route=db("route");

        $p_id=input("get.p_id");

        $package_id=input("get.package_id");

        $packageList=$route->where(["p_id"=>$p_id,"package_id"=>$package_id])->order("day_no asc")->select();

        foreach($packageList as $k=>$v){

            $sence=db("route_info")->where(["tr_id"=>$v['id'],"itype"=>7])->select();

            $packageList[$k]['sence']=$sence;

            $packageList[$k]['count']=count($sence);



        }

        // dump($packageList);



        if(request()->isPost()){

            $data=input("post.");

            foreach($data as $k=>$v){

                db("route_info")->where("id",$k)->setField("sort",$v);

            }

            $this->success("景点排序成功");





        }



        $this->assign([

            "list"=>$packageList,

            "p_id"=>$p_id,

            "package_id"=>$package_id,

        ]);

        return $this->view->fetch();

    }

    /*

     * 20200407

     * 田博

     * 行程天数排序

     * */

    public function route_day_sort(){

        $data=input("post.");

        $p_id=$data['p_id'];

        $package_id=$data['package_id'];

        $route=db("route");

        array_pop($data);

        array_pop($data);

        $count=count(array_unique($data));

        if(count($data)!=$count){

            $this->error("行程天数不得重复！","/admin/product/route_day?p_id={$p_id}&package_id={$package_id}");

        }

        foreach($data as $k=>$v){

            $route->where("id",$k)->setField("day_no",$v);

        }

        $this->redirect("/admin/product/route_day?p_id={$p_id}&package_id={$package_id}");

    }





    /*

     * 图库图片展示

     * 0409

     * 田博

     *

     * */

    public function product_gallery(){

        $route_info_id=input("get.route_info_id");

        $pid=input("get.pid");

        $day_no=input("get.day_no");



        $routeInfo=db("route_info")->where("id",$route_info_id)->find();

        $routeInfoRes=db("place")->where("id",$routeInfo['linkid'])->find();

        //$routeInfoRes=db("place")->where("p_name",$routeInfo['title'])->find();

        $routeInfoImgList=db("place_media")->where("place_id",$routeInfoRes['id'])->select();

        //dump($routeInfoImgList);

        $this->assign([

            "routeInfoImgList"=>$routeInfoImgList,

            "route_info_id"=>$route_info_id,

            "pid"=>$pid,

            "day_no"=>$day_no,

        ]);

        return $this->view->fetch();

    }



    /*裁切图片提交

     *   0410

     *   田博

     * */



    public function product_gallery_cut(){

        $route_info_img=db("route_info_img");

        $place_media=db("place_media");

        $str=input("get.str");

        $route_info_id=input("get.route_info_id");

        $pid=input("get.pid");

        $arr=explode("|",$str);

        $flag=0;

        for($i=0;$i<count($arr);$i++){

            $img=$place_media->find($arr[$i]);

            $data['imgadr']=$img['m_path'];

            $data['tri_id']=$route_info_id;

            $route_info_img->insert($data);

            if($i==(count($arr)-1)){

                $flag=1;

            }

        }

        //dump($flag);die;

        if($flag==1){

            ajaxMsg("景点裁切图片添加成功！",1);

        }else{

            ajaxMsg("景点裁切图片添加失败！",0);

        }





    }





    /*

 * 自费项目复制

 * 20200508

 * 田博

 * */

    public function chargeable_copy(){



        $product_selfpay=db("product_selfpay");

        $id=input("post.id");

        $res=$product_selfpay->where("id","=",$id)->find();

        //复制 0-总自费项目

        $result0=$this->product_selfpay_add($res,0);

        $list_type1=$product_selfpay->where(['pptype'=>1,"fid"=>$id])->select();

        foreach($list_type1 as $k=>$v){

            //1-自费项目类别

            $result1=$this->product_selfpay_add($v,$result0);

            $list_type2=$product_selfpay->where(['pptype'=>2,"fid"=>$v['id']])->select();

            foreach($list_type2 as $k1=>$v1){

                //2-自费项目组

                $result2=$this->product_selfpay_add($v1,$result1);

                $list_type3=$product_selfpay->where(['pptype'=>3,"fid"=>$v1['id']])->select();

                foreach($list_type3 as $k2=>$v2){

                    //3-自费项目

                    $result3=$this->product_selfpay_add($v2,$result2);

                    $this->product_spprice($v2['id'],$result3);

                }

            }

        }



        ajaxMsg("复制成功",1);

    }

    public function product_spprice($oldId,$newId){

        $product_spprice=db("product_spprice");

        $list=$product_spprice->where("sp_id","=",$oldId)->select();

        if(count($list)){

            foreach($list as $k=>$v){

                $data['p_id']=$v['p_id'];

                $data['sp_id']=$newId;

                $data['spp_id']=$v['spp_id'];

                $data['sppackageid']=$v['sppackageid'];

                $data['p_num']=$v['p_num'];

                $data['price']=$v['price'];

                $data['title']=$v['title'];

                $data['info']=$v['info'];

                $data['childrenprice']=$v['childrenprice'];

                $product_spprice->insertGetId($data);

            }

        }

    }

    public function product_selfpay_add($value,$fid){

        $data['pid']=$value['pid'];

        $data['fid']=$fid;

        $data['pptype']=$value['pptype'];

        $data['spp_id']=$value['spp_id'];

        $data['sppackageid']=$value['sppackageid'];//title

        $data['title']=$value['title'];

        $data['info']=$value['info'];

        $data['status']=$value['status'];

        $data['pa_order']=$value['pa_order'];

        $data['pricetype']=$value['pricetype'];

        $data['selecttype']=$value['selecttype'];

        $data['unit']=$value['unit'];

        $data['onehouse']=$value['onehouse'];

        $result=db("product_selfpay")->insertGetId($data);

        return $result;

    }





    /*

 * 后端产品评价

 * 20200512

 * 田博

 * */



    public function reviews(){

        $id=input("get.id");

        $userEvaluation=db("user_evaluation");

        $list=$userEvaluation->where("pid",$id)->select();

        $evaluation_score=getArr("evaluation-score");

        //dump($id);

        $this->assign([

            "eList"=>$list,

            "evaluation_score"=>$evaluation_score,

            "pid"=>$id,

        ]);

        return $this->view->fetch();

    }





 



    public function reviews_edit(){

        $id=input("get.id");

        $article_img=db("article_img");

        $userEvaluation=db("user_evaluation");

        $res=$userEvaluation->find($id);

        $evaluation_score=getArr("evaluation-score");

        $imgList=db("article_img")->where(["info_id"=>$id,"info_type"=>4])->select();

        $resArr=array_flip($evaluation_score);

        //dump($resArr);

        if(request()->isPost()){

            $data=input("post.");

            // dump($data);

            $count=count($data);

            if(!$res['userid']){

                $imgCount=$count-17;

            }else{

                $imgCount=$count-15;

            }

            

            $img_temp=$data['img_temp'];

            if(strpos($img_temp,"|")){

                $img_temp_arr=explode("|",$img_temp);

                $img_temp_arr_count=count($img_temp_arr);

                for($i=0;$i<$img_temp_arr_count;$i++){

                    if($img_temp_arr[$i]>0){

                        $res_article_img=$article_img->find($img_temp_arr[$i]);

                        if($res_article_img['imgadr']!=''){

                            $img_url1=ROOT_PATH . 'public'.$res_article_img['imgadr'];

                            @unlink($img_url1);

                        }

                        $article_img->delete($res_article_img['id']);

                    }

                }

            }





            if($imgCount>0){

                for($i=0;$i<$imgCount;$i++){

                    $imgURL=base64_image_content($data["img".$i]);

                    $img_url['imgadr']=$imgURL['url'];

                    $img_url['info_id']=$data['id'];

                    $img_url['info_type']=4;

                    $article=$article_img->insertGetId($img_url);

                }

            }



           if(!$res['userid']){

                if($data['userimg']){ 

                    $imgURLTou=base64_image_content($data["userimg"]);

                    $update['userimg']=$imgURLTou['url'];

                }else{

                    $update['userimg']="/assets/style/images/tou1.png";

                }

                $update['username']=$data['username'];

           }

            



            $update['pnum']=$data['pnum'];

            $update['pnum_info']=$data['pnum_info'];

            $update['guide_num']=$data['guide_num'];

            $update['guide_info']=$data['guide_info'];

            $update['trip_num']=$data['trip_num'];

            $update['trip_info']=$data['trip_info'];

            $update['food_num']=$data['food_num'];

            $update['food_info']=$data['food_info'];

            $update['service_num']=$data['service_num'];

            $update['traffic_info']=$data['traffic_info'];

           

            $update['mstatus']=$data['mstatus'];

            $update['pmsg']=$data['pmsg'];

            $update['id']=$data['id'];

            $update['updatetime']=strtotime($data['updatetime']);



            $updateRes=$userEvaluation->update($update);



            if($updateRes!==false){

                $this->success("修改成功","/admin/product/reviews?id={$res['pid']}");

            }else{

                $this->error("修改失败");

            }

        }



        $this->assign([

            "res"=>$res,

            "evaluation_score"=>$evaluation_score,

            "resArr"=>$resArr,

            "imgList"=>$imgList,

        ]);

        return $this->view->fetch();

    }



 



    public function reviews_add(){

        $pid=input("get.pid");

        $article_img=db("article_img");

        $userEvaluation=db("user_evaluation");

        if(request()->isPost()){

            $data=input("post.");

            $count=count($data);

            //dump($data);

            $imgCount=$count-17;

            if($data['updatetime']==""){

                $updateTime=time();

            }else{

                $updateTime=strtotime($data['updatetime']." ".date("H:i:s"));

            }

            if($data['userimg']==""){

                $update['userimg']="/assets/style/images/tou1.png";

            }else{

                $imgURLTou=base64_image_content($data["userimg"]);

                $update['userimg']=$imgURLTou['url'];

            }



            $update['pnum']=$data['pnum'];

            $update['pnum_info']=$data['pnum_info'];

            $update['guide_num']=$data['guide_num'];

            $update['guide_info']=$data['guide_info'];

            $update['trip_num']=$data['trip_num'];

            $update['trip_info']=$data['trip_info'];

            $update['food_num']=$data['food_num'];

            $update['food_info']=$data['food_info'];

            $update['traffic_num']=$data['traffic_num'];

            $update['traffic_info']=$data['traffic_info'];

            $update['service_num']=50;

            $update['mstatus']=$data['mstatus'];

            $update['pmsg']=$data['pmsg'];

            $update['username']=$data['username'];

            $update['fid']=0;

            $update['mtype']=0;

            $update['pid']=$pid;

            $update['updatetime']=$updateTime;

          

            $updateRes=$userEvaluation->insertGetId($update);

            if($imgCount>0){

                for($i=0;$i<$imgCount;$i++){

                    $imgURL=@base64_image_content($data["img".$i]);

                    $img_url['imgadr']=$imgURL['url'];

                    $img_url['info_id']=$updateRes;

                    $img_url['info_type']=4;

                    $article=$article_img->insertGetId($img_url);

                }

            }







            if($updateRes){

                $this->success("评论添加成功","/admin/product/reviews?id={$pid}");

            }else{

                $this->error("评论添加失败");

            }

        }



        $userList=db("user")->where("group_id",3)->select();



        foreach($userList as $k=>$v){

            $count=$userEvaluation->where("userid",$v['id'])->count();

            $userList[$k]['count']=$count;

        }



        $evaluation_score=getArr("evaluation-score");

        $resArr=array_flip($evaluation_score);

        $this->assign([

            "evaluation_score"=>$evaluation_score,

            "resArr"=>$resArr,

            "pid"=>$pid,

            "userList"=>$userList,

        ]);



        return $this->view->fetch();



    }



    public function reviews_del(){



        if(request()->isAjax()){}

        $id=input("post.id");

        $article_img=db("article_img");

        $articleImgList=$article_img->where(["info_id"=>$id,"info_type"=>4])->select();



        //dump($articleImgList);die;

        foreach($articleImgList as $k=>$v){

            $path=ROOT_PATH . 'public'.$v['imgadr'];

            @unlink($path);

            $res= $article_img->delete($v['id']);

            if(!$res){

                ajaxMsg("评论图片删除失败",0);

            }

        }

        $result=db("user_evaluation")->delete($id);



        if($result){

            ajaxMsg("评论删除成功",1);

        }else{

            ajaxMsg("评论删除失败",0);

        }



    }





















}

